假设我输入:“狗是哺乳动物”
我想在文本文档中搜索这句话。我如何在java中做到这一点?
System.out.println("Please enter the query :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
String[] array2 = word2.split(" ");这段代码接受字符串'dog is mammal‘,并分别处理每个标记。
例如:“狗是哺乳动物”
狗
是
哺乳动物
我希望将输入处理为
狗是哺乳动物
我不想让它单独处理它。我希望它将其作为单个字符串处理,并查找匹配项。谁能让我知道我的不足之处?
发布于 2011-03-14 19:06:24
如果您想将字符串作为一段文本处理,为什么要将字符串拆分成单词。我只会使用你的原始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<输入不是按单词拆分的。
发布于 2011-03-14 19:12:06
直接在文件中查找word2,如果已经解析了整个文件,则在文件中使用字符串indexof(word2)
发布于 2011-03-14 19:15:26
只需在阅读时将它们连接在一起:
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();
}https://stackoverflow.com/questions/5297705
复制相似问题