java 如何输入一个句子,以便程序将句子识别为单个单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5297705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:28:55  来源:igfitidea点击:

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

java

提问by Wai Loon II

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 ?

我想在文本文档中搜索这句话。我如何在 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 process 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 ?

我不希望它单独处理它。我希望它将它作为单个字符串处理并查找匹配项。任何人都可以让我知道我的不足之处吗?

回答by Peter Lawrey

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 word2you have which is the whole text AFAICS

如果要将 String 作为单个文本进行处理,为什么要将字符串拆分为单词。我只会使用word2您拥有的原始文本,即整个文本 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.

输入不会被单词分解。

回答by Nirmal- thInk beYond

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

word2直接在文件中查找,如果您已经解析了整个文件,则indexof(word2)在文件中使用字符串

回答by bezmax

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();
}