Search code examples
javastringstack

why are some words not checked or included in string of reversed words?


everyone. I have a task- reverse every word in a sentence as long as the word is 5 or more letters long. The program has been working with most words, but after a couple, the words are not included. Does anyone know why this is happening? Here is the code:

public static int wordCount(String str) {
    int count = 0;
    for(int i = 0; i < str.length(); i++) if(str.charAt(i) == ' ') count++;
    return count + 1;
}

This just gets the word count for me, which I use in a for loop later to loop through all the words.

public static String reverseString(String s) {
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        stack.push(s.charAt(i));
    }
    while (!stack.empty()) {
        sb.append(stack.pop());
    }
    return sb.toString();
}

This reverses a single string. This is not where I reverse certain words- this reverses a string. "Borrowed" from https://stackoverflow.com/a/33458528/16818831.

Lastly, the actual function:

public static String spinWords(String sentence) {
    String ans = "";
    for(int i = 0; i <= wordCount(sentence); i++) {
        if(sentence.substring(0, sentence.indexOf(' ')).length() >= 5) {
            ans += reverseString(sentence.substring(0, sentence.indexOf(' '))) + " ";
            sentence = sentence.substring(sentence.indexOf(' ') + 1);
        } else {
            ans += sentence.substring(0, sentence.indexOf(' ')) + " ";
            sentence = sentence.substring(sentence.indexOf(' ') + 1);
        }
    }
    return ans;
}

This is where my mistake probably is. I'd like to know why some words are omitted. Just in case, here is my main method:

public static void main(String[] args) {
    System.out.println(spinWords("Why, hello there!"));
    System.out.println(spinWords("The weather is mighty fine today!"));
}

Let me know why this happens. Thank you!


Solution

  • The main issue would appear to be the for loop condition in spinWords()

    The word count of your sentence keeps getting shorter while at the same time, i increases.

    For example:

    • i is 0 when the word count is 5
    • i is 1 when the word count is 4
    • i is 2 when the word count is 3
    • i is 3 when the word count is 2 which stops the loop.

    It can't get through the whole sentence.

    As many have mentioned, using the split method would help greatly, for example:

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