Java – String inversion, wrong result

String inversion, wrong result… here is a solution to the problem.

String inversion, wrong result

So my question is about getting inverted strings, but only words longer than or equal to 5 characters.
So, if we pass (“Hey fellow warriors”) to the method, we should get “Hey wollef sroirraw” as the return. My code gave me some weird results that = “sroirraw fellow warriors”.

Here is my code, please give me some clues. The space after the last word shouldn’t be returned, but I don’t know why that’s the case.

public class PrimeChecker {

public String spinWords(String sentence) {

String[] tablica = sentence.split(" ");

for ( String x : tablica ) {
        int y = 0;
        if (  x.length() >= 5 ) {
            StringBuilder p = new StringBuilder(x).reverse();
            x = p.toString();
        }
        tablica[y] = x;
        y++;            
    }

StringBuilder wynik = new StringBuilder();

for ( String z : tablica ) {
        int y = 0;
        tablica[y] = z;
        wynik.append(tablica[y]);
        if (tablica.length > 1 && y != tablica.length - 1 ) {
            wynik.append(" ");
        }
        y++;
    }
    return wynik.toString();
}   
}

Tester

public class PrimeCheckerTest {
    public static void main(String[] args) {
        PrimeChecker obiekt = new PrimeChecker();
        System.out.println(obiekt.spinWords("Hey fellow warriors").toString());     
    }
}

Solution

First, I prefer to split with \\s+ that matches one or more whitespace characters. Second, I’ll use lambda with Arrays.stream on the tag I split. Then I will map each word, inverting each word with 5 or more characters. This can be done with StringBuilder and reverse(). Since this method does not require any instance state, we can make it static. Finally, use Collector to connect the back of the words together. Like,

public static String spinWords(String sentence) {
    return Arrays.stream(sentence.split("\\s+"))
            .map(s -> s.length() >= 5 ? new StringBuilder(s).reverse().toString() : s)
            .collect(Collectors.joining(" "));
}

Test it

public static void main(String[] args) {
    System.out.println(spinWords("Hey fellow warriors"));
}

Which gives (as specified).

Hey wollef sroirraw

Related Problems and Solutions