How to capitalize the first and last letters of every word in a string
i have done it this way -
String cap = "";
for (int i = 0; i < sent.length() - 1; i++)
{
if (sent.charAt(i + 1) == ' ')
{
cap += Character.toUpperCase(sent.charAt(i)) + " " + Character.toUpperCase(sent.charAt(i + 2));
i += 2;
}
else
cap += sent.charAt(i);
}
cap += Character.toUpperCase(sent.charAt(sent.length() - 1));
System.out.print (cap);
It does not work when the first word is of more than single character
Please use simple functions as i am a beginner
Split the string into words and store it in the String array using regex. Take a for-each loop and store the first character by using subString() and store it in the “firstchar” and rest of the string store in “restchar” . Then add the “firstchar” and “restchar” string in “newstr”.
To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.
Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters. Note: The toLowerCase() method converts a string to lower case letters.
Using apache commons lang
library it becomes very easy to do:
String testString = "this string is needed to be 1st and 2nd letter-uppercased for each word";
testString = WordUtils.capitalize(testString);
testString = StringUtils.reverse(testString);
testString = WordUtils.capitalize(testString);
testString = StringUtils.reverse(testString);
System.out.println(testString);
ThiS StrinG IS NeedeD TO BE 1sT AnD 2nD Letter-uppercaseD FoR EacH WorD
You should rather split your String with a whitespace as character separator, then for each token apply toUpperCase() on the first and the last character and create a new String as result.
Very simple sample :
String cap = "";
String sent = "hello world. again.";
String[] token = sent.split("\\s+|\\.$");
for (String currentToken : token){
String firstChar = String.valueOf(Character.toUpperCase(currentToken.charAt(0)));
String between = currentToken.substring(1, currentToken.length()-1);
String LastChar = String.valueOf(Character.toUpperCase(currentToken.charAt(currentToken.length()-1)));
if (!cap.equals("")){
cap += " ";
}
cap += firstChar+between+LastChar;
}
Of course you should favor the use of StringBuilder over String as you perform many concatenations.
Output result : HellO World. AgaiN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With