2011-03-14 52 views
0

让我说我输入:'狗是哺乳动物'如何输入句子以便程序将句子识别为单个单词?

我想在文本文件中搜索这句话。我如何在java中做到这一点?

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

此代码段接受字符串'狗是哺乳动物',并分别处理每个令牌。

例如: '狗是哺乳动物'

>

>

>

>

哺乳动物

>

>

我想处理输入的

狗是哺乳动物

>

>

我犯规也想分开处理。我希望它将它作为单个字符串处理并查找匹配。任何人都可以让我知道我缺乏什么?

+0

字符串可以包含换行符。当您进行搜索时,他们会被视为与任何其他角色相同。 – glowworms 2011-03-14 11:17:18

回答

3

如果要将字符串处理为单个文本,为什么要将字符串拆分为单词。我只想用你有原来word2是整个文本AFAICS

编辑:如果我运行

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

我得到

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

输入不受字打散。

+0

我认为作者的意思是他正在获取多行输入,但想要将其作为单行文本输入到变量中。 – bezmax 2011-03-14 11:34:18

+0

@Max,我已经添加了一个例子,我不知道这些单词是如何被分解的。 – 2011-03-14 11:40:00

+1

谢谢你们..你们帮助我很多..感谢您的关注.. – 2011-03-14 12:06:50

0

直接在文件中找到word2,如果你已经解析整个文件,然后使用字符串indexof(word2)文件

0

只需concatinate他们都在阅读:

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