java“ stringtokenizer.nextToken(delimiter); ”如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5049934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does the java " stringtokenizer.nextToken(delimiter); " work?
提问by Darth Joshua
What i mean is what string values are accepted as delimiters? this is because i keep trying to use a string composed of several different characters but the program just seems to ignore it as just scan with empty space as the default delimiter...
我的意思是接受哪些字符串值作为分隔符?这是因为我一直在尝试使用由几个不同字符组成的字符串,但程序似乎只是忽略它,因为只是使用空格作为默认分隔符进行扫描...
For example if the tokenized string is as follows: Phone Number = 790-3233
例如,如果标记化的字符串如下:电话号码 = 790-3233
I would like the 1st token to be up to the " = " thus i set it as the delimiter and the next token should just be the string "790-3233"
我希望第一个标记达到“=”,因此我将其设置为分隔符,下一个标记应该只是字符串“790-3233”
Thanks in advance...
提前致谢...
回答by Dead Programmer
By Default the Delimiters is space
, if you do not supply one
默认情况下,分隔符是space
,如果您不提供一个
// Extracted StringTokenizer.java
public StringTokenizer(String string)
{
this(string, " \t\n\r\f", false);
}
If you supply =
as delimiter along with the string then it splits
如果您=
将分隔符与字符串一起提供,则它会拆分
StringTokenizer st = new StringTokenizer("Phone Number = 790-3233","=");
回答by Bart Kiers
Following the remark from the API docs:
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 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人改用 String 的 split 方法或 java.util.regex 包。
I'd use split in this case:
在这种情况下,我会使用 split:
String text = "Phone Number = 790-3233";
String[] tokens = text.split("\s*=\s*");
The regex \s*=\s*
matches zero or more space-chars, followed by an =
sign, followed by zero or more space-chars.
正则表达式\s*=\s*
匹配零个或多个空格字符,后跟一个=
符号,后跟零个或多个空格字符。