- Capitalize the first letter of each word in a string using Java
- You might also like.
- Capitalize last letter and Lowercase first letter of a word in Java
- To Show You Some Instances
- Instance-1
- Instance-2
- Instance-3
- Syntax
- Syntax
- Syntax
- Syntax
- Algorithm
- Algorithm-1
- Algorithm-2
- Multiple Approaches
- Approach-1: By Using Inbuilt substring Method
- Example
- Output
- Approach-2: By Using Inbuilt charAt() Method
- Example
- Output
- Java String Converts the first letter to lowercase
- Related
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.
Capitalize last letter and Lowercase first letter of a word in Java
String is a sequence of character values. In Java, Strings are considered as objects. We have a String class provided by Java for creating and manipulating strings.
We have to convert the first letter of the word to lowercase and last letter of the word to uppercase.
In this article we will see how the first and last letter can be converted into lower and upper case respectively. Let’s explore.
To Show You Some Instances
Instance-1
Suppose the input string is “Hello”
After converting the first letter to lower and last letter to capital, the new string will be “hellO”
Instance-2
Suppose the input string is “Java”
After converting the first letter to lower and last letter to capital, the new string will be “javA”
Instance-3
Suppose the input string is “Programming”
After converting the first letter to lower and last letter to capital, the new string will be “programminG”
Syntax
To get the length of the String Java String class provides a length() method.
Below is the syntax for that −
Where, str is the string variable.
To get a substring of the original string Java String class provides a substring() method.
Syntax
Below is the syntax for that −
str.substring(int startIndex); str.substring(int startIndex, int endIndex);
Where, startIndex is inclusive and endIndex is exclusive.
To get a character at a specified index Java String class provides the charAt() method.
Syntax
Below is the syntax for that −
Where, index refers to the index of the character that you need.
To convert different types of values to String value Java String class provides valueOf() method.
Syntax
Below is the syntax for that −
Algorithm
Note − This problem can be solved with the Array concept also. But here we have tried to solve the problem without using the array concept. Also we have used only inbuilt methods of String Class.
Algorithm-1
- Step 1 − Get the string/word either by initialization or by user input.
- Step 2 − Get the first and last letter by using the substring() method. Then convert it to lower and upper case by using toLowerCase() method and toUpperCase() method respectively.
- Step 3 − Get the middle characters (except first and last character) with the help of substring() method.
- Step 4 − Combine first, middle and last value and get the final string/word.
Algorithm-2
- Step 1 − Get the string/word either by initialization or by user input.
- Step 2 − Get the first and last letter by using charAt() method. Then convert it to lower and upper case by using toLowerCase() method and toUpperCase() method respectively.
- Step 3 − Get the middle characters (except first and last character) with the help of charAt() method and a for loop.
- Step 4 − Then combine first, middle and last value and get the final string/word.
Multiple Approaches
We have provided the solution in different approaches.
Let’s see the program along with its output one by one.
Approach-1: By Using Inbuilt substring Method
Example
In this approach, we will make use of Algorithm-1
import java.util.Scanner; public class Main < public static void main(String[] args) < //input string String str = "Java"; System.out.println("Original string is: "+str); //get size of the string int size = str.length(); //get last character and convert it to upper case String last = str.substring(size-1,size); String lastinUpper = last.toUpperCase(); //get first character and convert it to lower case String first = str.substring(0,1); String firstinLower = first.toLowerCase(); //get middle parts of the word, except first and last character String middle = str.substring(1,size-1); //combine everything and get the final string String result = firstinLower+middle+lastinUpper; //print result System.out.println("Updated string is: "+result); >>
Output
Original string is: Java Updated string is: javA
Approach-2: By Using Inbuilt charAt() Method
Example
In this approach, we will make use of Algorithm-2
public class Main < public static void main(String[] args) < //input String String str = "Python"; System.out.println("Original string: "+str); //get length of string int size = str.length(); //find last character and convert it to upper case char last = str.charAt(size-1); String finalLast = (String.valueOf(last)).toUpperCase(); //find first character and convert it to lowercase char first = str.charAt(0); String finalFirst = (String.valueOf(first)).toLowerCase(); //find middle characters String middle=""; for(int i=1; i//find the updated string String result = finalFirst+middle+finalLast; System.out.println("Updated string: "+result); > >
Output
Original string: Python Updated string: pythoN
In this article, we explored how to convert the first letter of a word to lowercase and last letter of the word to upper case in Java by using different approaches.
Java String Converts the first letter to lowercase
the string with the first letter in lowercase.
//package com.java2s; /*/*w w w . d e m o 2 s . c o m */ * Copyright 2001-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main < /** * Converts the first letter to lowercase * *
Example: FirstName => firstName *
Example: name => name *
Example: S => s * * @param s the string * @return the string with the first letter in lowercase. */ public static String firstLetterToLowerCase(String s) < if (s.length() > 1) < return Character.toLowerCase(s.charAt(0)) + s.substring(1); > else if (s.length() == 1) < return "" + Character.toLowerCase(s.charAt(0)); > else < return s; > > >
Related
- Java String Converts spaces and punctuation to underscores.
- Java String Converts the first char in a string to an lowercase letter and returns the string.
- Java String Converts the first character of string to upper case, appends to string builder, returns resulted string.
- Java String Converts the first letter to lowercase
- Java String displayNameConvert(String key)
- Java String emptyConvert(String str, String str1)
- Java String Encodes an input character (not null) to XML attributes format.
Call the encodeXML( string ) method and convert the following characters : ‘\n’, ‘\r’, ‘\t’ and ‘\»‘ to their corresponding code.
demo2s.com | Email: | Demo Source and Support. All rights reserved.