Answer the question
In order to leave comments, you need to log in
How in StringBuilder to separate words with spaces in a loop?
In the loop, you need to iterate over the words and process them. There must be spaces between words. If you do this, the space will be trimmed at the end. How to make it so that there are spaces inside the sentence, but without trim?
public String makeSothing(String text) {
StringBuilder result = new StringBuilder();
String[] words = text.split(" ");
for (String word : words) {
result.append(reverseWord(word)).append(" ");
}
return result.toString();
}
Answer the question
In order to leave comments, you need to log in
Use String Joiner.
Or keep track of the last element in a loop with counters.
public String makeSothing(String text) {
StringBuilder result = new StringBuilder();
String[] words = text.split(" ");
if (words.length > 0) {
result.append(reverseWord(words[0]));
}
for (int i = 1; i < words.length; i++) {
result.append(" ").append(reverseWord(words[i]));
}
return result.toString();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question