Arturo
Arturo

Reputation: 4180

Get second word of String not recognized

I have the following code:

String myString = "Hello world";

firstWord = myString.substring(0, myString.indexOf(" "));
secondWord= myString.substring(1, myString.indexOf(" "));

The first word is being recognized but the second one is actually cutting a character. So:

first: Hello

Second: ello

How can I get the second word?

Thank you

Upvotes: 1

Views: 271

Answers (3)

Kishore Prakash
Kishore Prakash

Reputation: 1

secondWord= myString.substring(1, myString.indexOf(" "));

Why your code didn't work: For the above line of code, you are starting at "1" index of the string. Index one starts at "e" because you start counting from 0. So, When you start at "e" and stop at the next space, " ", that wouldn't' work, because it will just throw the words between "e" and " ". Which ends up being ello (note. it doesn't include space)

To fix this run: secondWord= myString.substring(myString.indexOf(" "), 11); or secondWord= myString.substring(6, 11);

Note the ending index, for example, 11 in our case from the myString.substring(6, 11), is one plus(+) the current computer index. In this case, the letter "d" was indexed 10 but you always add one to the ending index.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271135

If you are sure that there are exactly 2 words, then you can just do this:

String myString = "Hello World";
int indexOfFirstSpace = myString.indexOf(" ");
String firstWord = myString.substring(0, indexOfFirstSpace);
String secondWord = myString.substring(indexOfFirstSpace + 1);

The second word is the just the substring from the index after the index of the space, all the way to the end of the string.

If you are not sure how many words there are, you might as well use split to split the string:

String[] words = myString.split(" ");
if (words.length >= 2) {
    String firstWord = words[0];
    String seconfWord = words[1];
}

Upvotes: 3

puneet agarwal
puneet agarwal

Reputation: 51

    String myString = "Hello world";
    index(" ") will always give you the index of first occurrence of " ". So in
    String firstWord = myString.substring(0, myString.indexOf(" "));
    you start with character at 0th index and end index will be first occurrence " " which is not included.
    Hello

    Now in your second 
    String secondWord= myString.substring(1, myString.last indexOf(" "));
    you are going to start with second character.
    ello

    **If you want to get words based in space as a separator the right way is to use split**

    **Example**
    String[] words = myString.split("\\s+");
    firstWord = words[0];
    secondWord = words[1];

Upvotes: 1

Related Questions