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

12,670

Solution 1

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

Solution 2

That's great that your problem is solved but it would be great if you try to use some built in functions(like String.split()) and libraries in your code as it can reduce a lot of processing and make your code more robust and independent of String length and other parameters.

Your code could be optimized to this level...

 class wordSep{
    public static void main(String args[]){
        String line = "The world is full of strangers";
        String[] word = line.split(" ");
        for(String str: word){
            System.out.println(str);
        }
    }
}

output -

The
world
is
full
of
strangers

Now you can also use String Tokenizer But it is not recommended any more...

Read this -> to completely understand how to split Strings in Java on some character, or using some Regex and other parameters

Share:
12,670
patmarley
Author by

patmarley

Updated on June 04, 2022

Comments

  • patmarley
    patmarley almost 2 years

    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.