Am Looping through a sentence splitting it to capitalize.But its hard to build it back after getting the individual words.
String str = "Not the answer you're looking for.";
StringBuilder stringBuilder = new StringBuilder();
String oneWord =" ";
for (String word : str.toLowerCase().split(" ")){
char firstLetter = word.substring(0,1).toUpperCase().charAt(0);
oneWord = firstLetter + word.substring(1);
System.out.println(stringBuilder.append(oneWord + " "));
}
}
I expect to get only one fully built String "Not The Answer You're Looking For."
String str = "Not the answer you're looking for.";
StringBuilder stringBuilder = new StringBuilder();
String oneWord =" ";
for (String word : str.toLowerCase().split(" ")){
char firstLetter = word.substring(0,1).toUpperCase().charAt(0);
oneWord = firstLetter + word.substring(1);
stringBuilder.append(oneWord + " ");
}
System.out.println(stringBuilder.toString());
You are not getting just one string because you use System.out.println
inside for
loop.
Consider my example above
oneWord += firstLetter + word.substring(1) + " ";
after loop
oneWord = oneWord.trim();
System.out.println(oneWord);
So the solution is:
String str = "Not the answer you're looking for.";
StringBuilder sb = new StringBuilder();
for (String word : str.toLowerCase().split(" ")) {
sb.append(str.substring(0, 1).toUpperCase());
sb.append(str.substring(1));
sb.append(" ");
}
System.out.println(stringBuilder.toString().trim());
Also your solution is not optimal. Check String.join() or use somth like this
Arrays.stream(str.toLowerCase().split(" "))
.map(word -> str.substring(0, 1).toUpperCase() + str.substring(1))
.collect(Collectors.joining(" "));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.