简体   繁体   中英

How to find the characters of the second word in a phrase using indexOf(); and char method?

I want to find the characters of the second word in a phrase using indexOf(); method and charAt(); You have to assume that the phrase will always have 3 words and that the second words will always have 5 letters. Sample input is "The white horse" ------> output is: Second word is 'white'

I have to achieve this without loops, built-in methods of java like substring, split...etc Here is my attempt but it keeps giving me one character: It should be constant that means it should always be 5, I think its the use of a print statement 5 times

else if (option == 4){
            int start = phrase.indexOf(' ');
            int end = phrase.indexOf(' ', start + 1);
            int length = end - start - 1;
            char n = phrase.charAt(length+2);
                System.out.print("Second word is '"+n+"'");
    }

Quoting the requirements, and highlighting the important ones:

Find the characters of the second word in a phrase using indexOf() method and charAt() . You have to assume that the phrase will always have 3 words and that the second word will always have 5 letters .

Can't use substring or any loops.

Seems you have to do it like this:

String phrase = "The white horse";

int idx = phrase.indexOf(' ');
System.out.println("Second word is '" + phrase.charAt(idx + 1)
                                      + phrase.charAt(idx + 2)
                                      + phrase.charAt(idx + 3)
                                      + phrase.charAt(idx + 4)
                                      + phrase.charAt(idx + 5) + "'");

Or like this:

String phrase = "The white horse";

int idx = phrase.indexOf(' ');
System.out.print("Second word is '");
System.out.print(phrase.charAt(idx + 1));
System.out.print(phrase.charAt(idx + 2));
System.out.print(phrase.charAt(idx + 3));
System.out.print(phrase.charAt(idx + 4));
System.out.print(phrase.charAt(idx + 5));
System.out.println("'");

Simple solution:

String[] words = phrase.split(" ");
System.out.print("Second word is '"+words[1]+"'");

Solution using only charAt() and indexOf()

int start = phrase.indexOf(' ');
int end = phrase.indexOf(' ', start + 1);

System.out.print("Second word is '");
for (int i=start+1; i<end; i++) {
   System.out.print(phrase.charAt(i));
}
System.out.print("'");

use this to achieve the second word:

final String ans = input.split(" ")[1];

or try repeating your code 5 times with icreasing your index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM