Java string capitalize all

What is WordUtils.capitalize in Java?

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

capitalize is a static method of the WordUtils class that is used to capitalize all delimiter-separated words in a string. Each word’s initial character is altered only.

  • The set of delimiters that separate the words can be passed to the method.
  • If no delimiters are specified, whitespace is considered to be the delimiter by default.

WordUtils is defined in the Apache Commons Text package. Apache Commons Text can be added to the Maven Project by adding the following dependency to the pom.xml file.

 org.apache.commons commons-text 1.9  

For other versions of the commons-text package, refer to the Maven Repository.

You can import the WordUtils class as follows:

import org.apache.commons.text.WordUtils; 

Syntax

public static String capitalize(final String str, final char. delimiters) 

Parameters

  • final String str : string to be capitalized
  • final char. delimiters : set of delimiters

Returns

This method returns a new capitalized string.

Code

import org.apache.commons.text.WordUtils;
public class Main
public static void main(String[] args)
String string = "Hello educative,how are you?";
System.out.print("Delimited by whitespace - ");
System.out.print(WordUtils.capitalize(string));
System.out.print("\nDelimited by comma (,) - ");
System.out.print(WordUtils.capitalize(string, ','));
string = "lorem ipsum is a pseudo-Latin text used in web design,typography,layout,and printing in place of english to emphasise design elements over content.it's also called placeholder (or filler) text.";
System.out.print("\nDelimited by comma (, and .) - ");
System.out.print(WordUtils.capitalize(string, ',', '.'));
>
>

Example 1

Applying the capitalize function will result in: Hello Educative,how Are You? .

The word how is not capitalized, as it’s not delimited by whitespace.

Example 2

Applying the capitalize function will result in: Hello educative,How are you?

Here, the comma is the delimiter and hence results in two fragments, i.e., Hello educative and how are you? . Capitalizing the first character of each fragment results in Hello educative,How are you?

Example 3

  • string = «lorem ipsum is a pseudo-Latin text used in web design,typography,layout,and printing in place of english to emphasise design elements over content.it’s also called placeholder (or filler) text.»
  • delimiters = [‘,’, ‘.’]

Applying the capitalize function will result in: Lorem ipsum is a pseudo-Latin text used in web design,Typography,Layout,And printing in place of english to emphasise design elements over content.It’s also called placeholder (or filler) text.

Here, the function capitalizes the first character of each fragment, separated by a comma or a full-stop.

Источник

Capitalize the first letter of each word in a string using Java

In this short guide, you will learn how to capitalize the first letter of each word in a string using Java. We have already learned to capitalize the first letter of a string in Java. But capitalizing each word in a string is a bit tricky.

The easiest way to capitalize the first character of each word of a string is by using Java 8 Stream API:

String str = "welcome to java"; // uppercase first letter of each word String output = Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1)) .collect(Collectors.joining(" ")); // print the string System.out.println(output); // Welcome To Java 

In the above example, we first split the string into an array using the split() method. The array is passed to Arrays.stream() as a parameter that turns it into a Stream object. Afterward, we use the map() method from streams to capitalize each word before converting it back to a string using the collect() method. If the string is empty or null , the above code will throw an exception. Let us write a function capitalizeAll() that makes sure there is no exception while transforming string:

public static String capitalizeAll(String str)  if (str == null || str.isEmpty())  return str; > return Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1)) .collect(Collectors.joining(" ")); > 
System.out.println(capitalizeAll("welcome to java")); // Welcome To Java System.out.println(capitalizeAll("this is awesome")); // This Is Awesome System.out.println(capitalizeAll("mcdonald in lahore")); // Mcdonald In Lahore System.out.println(capitalizeAll(null)); // null 

The above solution only changes the first letter of each word while all other characters remain the same. Sometimes, you want to ensure that only the first character of a word is capitalized. Let us write another function capitalizeFully() for this:

public static String capitalizeFully(String str)  if (str == null || str.isEmpty())  return str; > return Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); > 

The only difference between capitalizeAll() and capitalizeFully() is that the latter function explicitly changes the remaining part of the word to lowercase:

System.out.println(capitalizeFully("i aM aTTa")); // I Am Atta System.out.println(capitalizeFully("fOo bAr")); // Foo Bar 

If you are using Java 9 or higher, it is possible to use a regular expression with the String.replaceAll() method to capitalize the first letter of each word in a string. The String.replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement. Here is an example:

public static String capitalizeAll(String str)  if (str == null || str.isEmpty())  return str; > return Pattern.compile("\\b(.)(.*?)\\b") .matcher(str) .replaceAll(match -> match.group(1).toUpperCase() + match.group(2)); > 
System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java System.out.println(capitalizeAll("i am atta")); // I Am Atta System.out.println(capitalizeAll(null)); // null 

The Apache Commons Text library is yet another option to convert the first character of each word in a string to uppercase. Add the following dependency to your build.gradle file:

implementation 'org.apache.commons:commons-text:1.8' 
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-textartifactId> version>1.8version> dependency> 

Now you can use the capitalize() method from the WordUtils class to capitalize each word in a string:

System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky! System.out.println(WordUtils.capitalize(null)); // null 

The good thing about WordUtils methods is that they handle the exceptions gracefully. There won’t be any exception even if the input is null . The WordUtils class also provides the capitalizeFully() method that capitalizes the first character and turns the remaining characters of each word into lowercase:

System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue! 

You might also like.

Источник

Java string capitalize all

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Canvas python tkinter круг
Оцените статью