Search code examples
javastringsubstringindexofseparator

Separating words from a string using indexOf & substring methods in Java


Yo, I'm trying to write a program in Java that separates words from a string, using only substring and indexOf. I've already made this code and it runs almost perfect but it prints alot of empty line after printing the words.

class wordSep{
    public static void main(String args[]){
        String line = "The world is full of strangers";
        String word = line.substring(0,line.indexOf(" "));
        int index = line.length()-1;
        while(index>=0){
            System.out.println(word);
            line = line.substring(line.indexOf(" ") + 1) + " ";
            word = line.substring(0,line.indexOf(" "));
            index--;
        }
    }
}

The output of this will be:

The
world
is
full
of
strangers
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line

I think this has to do with the condition of my while loop. I need to have an output without those empty lines.. Please help, thanks.


Solution

  • Replace while(index>=0) with while(!word.isEmpty()) and get rid of index