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:
[java]
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());
}
}
[/java]
Output:
[plain]
Javadomain.in –> Proud To Be A Programmer!
[/plain]
Java Program to convert all words first letter to Small or LowerCase:
[java]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());
}
}
[/java]
Output:
[plain]
ngdeveloper.com –> proud to be a programmer!
[/plain]
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,
[java]
if (strBuff.charAt(nav) == ‘,’) {
isCaps = false;
} else if (!isCaps && !Character.isWhitespace(strBuff.charAt(nav))) {
strBuff.setCharAt(nav, Character.toLowerCase(strBuff.charAt(nav)));
isCaps = true;
}
[/java]