开发者

how to i input a sentence so that the program will recognize the sentence as a single word?

lets say i input : 'dog is mammal'

i would like to search for this sentence in a text document. How do i do this in java ?

    System.out.println("Please enter the query  :");
    Scanner scan2 = new Scanner(System.in);
    String word2 = scan2.nextLine();
    String[] array2 = word2.split(" ");

this code snippet accepts the string 'dog is mammal' and p开发者_Python百科rocess each tokens separately.

For example : 'dog is mammal'

dog

>

>

is

>

>

mammal

>

>

i would like to process the input as

dog is mammal

>

>

I doesnt want it to process it separately. I wanted it to process it as a single string and look for matches. Can anyone let me know where i am lacking ?


If you want to process the String as a single piece of text, why split up the string into words. I would just use the original word2 you have which is the whole text AFAICS

EDIT: If I run

System.out.println("Please enter the query  :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
System.out.println(">"+word2+"<");

I get

Please enter the query  :
dog is mammal
>dog is mammal<

The input is not broken up by word.


find word2 directly in file, and if you has parsed whole file then use string indexof(word2) in file


Simply concatinate them all while reading:

public String scanSentence() {
    Scanner scan2 = new Scanner(System.in);
    StringBuilder builder = new StringBuilder();
    String word2;
    //I do not know how you want to terminate input, so let it be END word.
    //If you will be reading from file - change it to "while ((word2 = scan2.nextLine()) != null)"
    //Notice the "trim" part
    while (!(word2 = scan2.nextLine().trim()).equals("END")) { 
        builder.append(word2);
        builder.append(" ");
    }

    return builder.toString().trim();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜