Change all words first letter to uppercase/lowercase in a string

Change all words first letter to uppercase/lowercase in a string

Change all words first letter to uppercase/lowercase in a string:

When you are getting particular string from different source and like to format all the different source strings to some particular format like all first letter to uppercase/lowercase, you can make use of the below given java program.
.toUpperCase() & .toLowerCase()

toUpperCase and toLowerCase in java will convert all the letters to uppercase/lowercase instead of converting only first letter of a string.
Java Program to convert all words first letter to Caps or UpperCase:

package in.javadomain;

public class ChangeAllWordsCaps {

public static void main(String[] args) {
String input = "ngdeveloper.com --> Proud to be a programmer!";
boolean isCaps = false;
StringBuffer strBuff = new StringBuffer(input);
int nav = 0;
while (nav < strBuff.length()) {
if (strBuff.charAt(nav) == ' ') {
isCaps = false;
} else if (!isCaps) {
strBuff.setCharAt(nav, Character.toUpperCase(strBuff.charAt(nav)));
isCaps = true;
}
nav++;
}
System.out.println(strBuff.toString());

}
}

Output:

Javadomain.in --> Proud To Be A Programmer!

Java Program to convert all words first letter to Small or LowerCase:

package in.javadomain;

public class ChangeAllWordsCaps {

public static void main(String[] args) {
String input = "ngdeveloper.com --> Proud to be a programmer!";
boolean isCaps = false;
StringBuffer strBuff = new StringBuffer(input);
int nav = 0;
while (nav < strBuff.length()) {
if (strBuff.charAt(nav) == ' ') {
isCaps = false;
} else if (!isCaps) {
strBuff.setCharAt(nav, Character.toLowerCase(strBuff.charAt(nav)));
isCaps = true;
}
nav++;
}
System.out.println(strBuff.toString());

}
}

Output:

ngdeveloper.com --> proud to be a programmer!

What we are doing here ?

We are checking the given string character by character and when the word fall next to empty space then we are converting to lower/upper case.
If you want to convert the words first letter to lower/upper after ,: then just give the same in the program this way,

 

if (strBuff.charAt(nav) == ',') {
isCaps = false;
} else if (!isCaps && !Character.isWhitespace(strBuff.charAt(nav))) {
strBuff.setCharAt(nav, Character.toLowerCase(strBuff.charAt(nav)));
isCaps = true;
}

 

474 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *