S
S
striver2019-12-07 17:42:31
Java
striver, 2019-12-07 17:42:31

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

2 answer(s)
I
illuzor, 2019-12-07
@striver

Use String Joiner.
Or keep track of the last element in a loop with counters.

S
striver, 2019-12-07
@striver

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 question

Ask a Question

731 491 924 answers to any question