gpt4 book ai didi

java - 将多个定界符传递给 StringTokenizer 构造函数

转载 作者:行者123 更新时间:2023-11-30 07:40:25 24 4
gpt4 key购买 nike

我已经看到将多个定界符(例如“.”、“?”、“!”)传递给 StringTokenizer 构造函数的语法是:

StringTokenizer obj=new StringTokenizer(str,".?!");

我没有得到的是,我用双引号将所有定界符括起来,所以这不会使它成为一个字符串而不是单独的人物。 StringTokenizer 类如何将它们识别为单独的字符?为什么是 ”。?!”不被视为单个分隔符?

最佳答案

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.

所以使用String#split相反。

String[] elements = str.split("\\.\\?!"); // treats ".?!" as a single delimiter
String[] elements2 = str.split("[.?!]"); // three delimiters

如果您怀念StringTokenizerEnumeration 特性,请获取Iterator

Iterator<String> iterator = Arrays.asList(elements).iterator();
while (iterator.hasNext()) {
String next = iterator.next();
// ...
}

How does the StringTokenizer class identify them as separate characters?

这是一个实现细节,不应该是您关心的问题。 There are a couple of ways to do that.他们使用 String#charAt(int)String#codePointAt(int)

Why is ".?!" not treated as a single delimiter?

这就是他们做出的选择:“我们将采用一个字符串,我们将在那里寻找分隔符s。” Javadoc 说得很清楚。

 *
* @param str a string to be parsed.
* @param delim the delimiters.
* @param returnDelims flag indicating whether to return the delimiters
* as tokens.
* @exception NullPointerException if str is <CODE>null</CODE>
*/
public StringTokenizer(String str, String delim, boolean returnDelims) {

关于java - 将多个定界符传递给 StringTokenizer 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57809572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com