标记化似乎在新分隔符之后的令牌中包含分隔符



问题的程序是一个电话簿应用程序,它接受格式化的用户输入(例如 ADD SampleName;SamplePhoneNumber;SampleCategory )。

此方法应该将其分为四个String

  • 命令"添加"
  • 其他 3 个令牌中的每一个。

第一个分隔符是空格,另外两个是;。 当我使用以下代码时,出于某种原因,包含一个空格作为 SampleName 的前缀。 我不知道为什么会发生这种情况,或者如何以实际的方式纠正这一点。 我习惯了C++,我只是在学习Java。 任何建议不胜感激。

方法如下:

public static Vector tokenize(String com)
{
   Scanner scanner = new Scanner(com);
Vector vs = new Vector();
String s;
while(scanner.hasNext())
{
    if(vs.size()==0)
    {
                scanner.useDelimiter("\p{javaWhitespace}+");
                s = scanner.next();  // Sets the first delimiter to ' '
                scanner.useDelimiter("[;]");
    }
    else
    {
                scanner.useDelimiter("[;]");
                s = scanner.next();  // Sets all other delimiters as ';'
    }
    vs.add(s);  //  Adds the string s to the vector of strings vs
}
return vs;
}

切换分隔符后,似乎会保留多余的空格。您可以通过始终使用相同的分隔符来轻松解决此问题:

public static Vector tokenize(final String com) {
    Scanner scanner = new Scanner(com);
    scanner.useDelimiter("[;\p{javaWhitespace}]+");
    Vector vs = new Vector();
    while (scanner.hasNext()) {
        vs.add(scanner.next()); // Adds the string to the vector of strings vs
    }
    return vs;
}

or this

public static Vector tokenize(final String com) {
    String[] tokens = com.split(" |;");
    Vector<String> vs = new Vector<String>(tokens.length);
    for (String s : tokens) {
            vs.add(s);
    }
    return vs;
}

最新更新