简体   繁体   English

Java 中的字符串标记器

[英]String Tokenizer in Java

I am using String Tokenizer in my program to separate strings.我在我的程序中使用 String Tokenizer 来分隔字符串。 Delimiter I am trying to use is ");".我尝试使用的分隔符是“);”。 But I found out that StringTokenizer uses ) and;但我发现 StringTokenizer 使用 ) 和; as 2 different delimiters.作为2个不同的分隔符。 But I want to use it as combined.但我想结合使用它。 How can I do it?我该怎么做?

my code:我的代码:

StringTokenizer st = new StringTokenizer(str,");");
String temp[] = new String[st.countTokens()];
while(st.hasMoreTokens()) { 
    temp[i]=st.nextToken();
    i++;
}

Thanks谢谢

As an alternative to String#split (StringTokenizer is deprecated), if you like Commons Lang, there is StringUtils#splitByWholeSeparator (null-safe, and no need to mess with regular expressions):作为 String#split 的替代方案(不推荐使用 StringTokenizer),如果您喜欢 Commons Lang,可以使用StringUtils#splitByWholeSeparator (null 安全,并且无需使用正则表达式):

 String temp[] = splitByWholeSeparator(str, ");" );

As many of the answers have suggested, String.split() will solve your problem.正如许多答案所建议的那样, String.split()将解决您的问题。 To escape the specific sequence you're trying to tokenize on you will have to escape the ')' in your sequence like this:要转义您尝试标记的特定序列,您必须像这样转义序列中的“)”:

str.split("\\);");

Anything wrong with this?这有什么问题吗?

String temp[] = str.split("\\);");

You should try with the split(String regex) method from the String class.您应该尝试使用 String class 中的 split(String regex) 方法。 It should work just fine, and I guess it returns an array of Strings ( just like you seem to prefer).它应该工作得很好,我猜它返回一个字符串数组(就像你似乎更喜欢的那样)。 You can always cast to a List by using Arrays.asList() method.您始终可以使用 Arrays.asList() 方法转换为列表。

Cheers, Tiberiu干杯,提比留

"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." “StringTokenizer 是一个遗留的 class,尽管在新代码中不鼓励使用它,但出于兼容性原因保留它。建议任何寻求此功能的人使用 String 的拆分方法或 java.util.regex ZEFE90A8E604A7C840D88D。”

Thats what Sun's doc says.这就是 Sun 的医生所说的。

String[] result = "this is a test".split("\\s");

Is the recommended way to tokenize String.是标记化字符串的推荐方法。

This will work for you.这对你有用。

import java.util.StringTokenizer;


public class StringTest {

/**
 * @param args
 */
public static void main(String[] args) {
    int i = 0;
    String str = "one);two);three);four";
    StringTokenizer st = new StringTokenizer(str, ");");
    String temp[] = new String[st.countTokens()];

    while (st.hasMoreTokens()) {

        temp[i] = st.nextToken();
        System.out.println(temp[i]);
        i++;
    }



}

}

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

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