【问题标题】:I want to search for a string using StringTokenizer but the string I'm looking for has a delimiter in it - Java我想使用 StringTokenizer 搜索一个字符串,但我正在寻找的字符串中有一个分隔符 - Java
【发布时间】:2012-01-11 03:25:43
【问题描述】:

我有一个名为quotes.txt 的外部文件,我将向您展示该文件的一些内容:

1 Everybody's always telling me one thing and out the other.
2 I love criticism just so long as it's unqualified praise.
3 The difference between 'involvement' and 'commitment' is like an eggs-and-ham 
  breakfast: the chicken was 'involved' - the pig was 'committed'.

我用过这个:StringTokenizer str = new StringTokenizer(line, " .'");

这是搜索的代码:

String line = "";
boolean wordFound = false;

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

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

现在,我想在第 1 行和第 2 行中搜索字符串 "Everybody's""it's",但它不起作用,因为撇号是分隔符之一。如果我删除该分隔符,那么我将无法在第 3 行搜索 "involvement""commitment""involved""committed"

我可以用什么合适的代码来解决这个问题?请帮忙,谢谢。

【问题讨论】:

    标签: java stringtokenizer


    【解决方案1】:

    我建议为此使用正则表达式 (the Pattern class) 而不是 StringTokenizer。例如:

    final Pattern targetWordPattern =
        Pattern.compile("\\b" + Pattern.quote(targetWord) + "\\b",
                        Pattern.CASE_INSENSITIVE);
    
    String line = "";
    boolean wordFound = false;
    
    while((line = bufRead.readLine()) != null) {
        if(targetWordPattern.matcher(line).find()) {
            wordFound = true;
            break;
        }
        else
            output = "Quote not found";
    }
    

    【讨论】:

    • 谢谢。但这会自动忽略这种情况吗?
    • @user1141418:不客气!还有——你在Pattern.compile 的调用中看到Pattern.CASE_INSENSITIVE 标志了吗?这就是告诉它忽略大小写的原因(或者在正则表达式中,执行“不区分大小写”的匹配)。
    • 嗨,我的程序仍有问题。我可以通过向我发送您的电子邮件来请求您的帮助,以便我可以向您展示整个代码吗?请和谢谢。
    • @user1141418:我不会在 StackOverflow 上发布我的电子邮件地址,但如果您发布您的,我会通过电子邮件发送给您。
    【解决方案2】:

    用空格标记,然后用 ' 字符修剪。

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 2012-01-08
      • 2020-08-31
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2014-11-10
      • 2015-02-07
      相关资源
      最近更新 更多