简体   繁体   English

StringTokenizer似乎在我的程序中不起作用-Java

[英]StringTokenizer does not seem to work in my program - Java

I am making a program about client/server programming in which the user will input a string in the console, and the program will search through every line of a .txt file for that string, and outputs the whole line where that particular string resides. 我正在编写一个有关客户端/服务器编程的程序,其中用户将在控制台中输入一个字符串,该程序将在.txt文件的每一行中搜索该字符串,并输出该特定字符串所驻留的整行。

This is a part of the code where the StringTokenizer is used: 这是使用StringTokenizer的代码的一部分:

String line = "";
boolean wordFound = false;

while((line = bufRead.readLine()) != null) {
    StringTokenizer str = new StringTokenizer(line, ", .();:-?!'");

    while(str.hasMoreTokens()) {
        String next = str.nextToken();
        if(next.equalsIgnoreCase(targetWord)) {
            wordFound = true;
            output = line;
            break;
        }
    }

    if(wordFound) break;
    else output = "Quote not found.";
}    

The problem is that when I want to search for a string eg "you're" or "it's my birthday" (with apostrophe and/or spaces), it gives a false value for boolean wordFound. 问题是,当我要搜索字符串(例如“您是”或“这是我的生日”)(带有撇号和/或空格)时,它会为布尔型wordFound提供错误的值。 I tried removing the delimiters " " and "'" but still it doesn't work. 我尝试删除定界符“”和“'”,但仍然无法正常工作。

I once modified the code and I sometimes get a true value for boolean wordFound, but now it seems like it does not ignore the case. 我曾经修改过代码,有时会获得boolean wordFound的真实值,但现在看来它并没有忽略这种情况。 eg I entered "you're", wordFound becomes true. 例如,我输入“ you're”,wordFound变为true。 But if I change it to "You're" or "yOu'Re", wordFound is still false. 但是,如果我将其更改为“ You're”或“ yOu'Re”,则wordFound仍然为false。

Can someone help me find a solution to this problem? 有人可以帮我找到解决这个问题的方法吗? Thanks. 谢谢。

Your string tokenizer should be: 您的字符串标记器应为:

StringTokenizer str = new StringTokenizer(line, ", .();:-?!\"");

In your code you have StringTokenizer(line, ", .();:-?!'"); 在您的代码中,您具有StringTokenizer(line, ", .();:-?!'"); ie ' instead of " , which is tokenizing your text you're" into you and re" . '替代"这是令牌化你的文字you're"youre"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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