[英]String Tokenizer missing 2 values off array
I am taking creating a StringTokenizer
like so and populating an ArrayList
using the tokens: 我正在像这样创建一个
StringTokenizer
,并使用标记填充ArrayList
:
LogUtils.log("saved emails: " + savedString);
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
for (int i = 0; i < st.countTokens(); i++) {
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
LogUtils.log("mListEmailAddresses: emails: " + mListEmailAddresses.toString());
11-20 09:56:59.518: I/test(6794): saved emails: hdhdjdjdjd,rrfed,ggggt,tfcg,
11-20 09:56:59.518: I/test(6794): mListEmailAddresses: emails: [hdhdjdjdjd, rrfed]
As you can see mListEmailAddresses
is missing 2 values off the end of the array. 如您所见,
mListEmailAddresses
在数组末尾缺少2个值。 What should I do to fix this. 我应该怎么做才能解决这个问题。 From my eyes the code looks correct but maybe I am misunderstanding something.
在我看来,代码看起来是正确的,但也许我误会了一些东西。
Thanks. 谢谢。
using hasMoreTokens
is the solution 使用
hasMoreTokens
是解决方案
while(st.hasMoreTokens()){
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
Use the following while loop 使用以下while循环
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
while (st.hasMoreTokens()) {
String strEmail = st.nextToken();
mListEmailAddresses.add(strEmail);
}
Note, you don't need to call toString
, nextToken
will return the string. 注意,您不需要调用
toString
, nextToken
将返回字符串。
Alternatively, you could use the split
method 或者,您可以使用
split
方法
String[] tokens = savedString.split(",");
mListEmailAddresses = new ArrayList<String>();
mListEmailAddresses.addAll(Arrays.asList(tokens));
Note, the API docs for StringTokenizer
state: 请注意,用于
StringTokenizer
状态的API文档:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.
StringTokenizer是一个遗留类,出于兼容性原因而保留,尽管在新代码中不鼓励使用它。 It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
建议任何寻求此功能的人改用String的split方法或java.util.regex包。
st.countTokens()
method calculates the number of times that this tokenizer's nextToken()
method can be called before it generates an exception. st.countTokens()
方法计算此tokenizer's nextToken()
方法在生成异常之前可以被调用的次数。 The current position is not advanced. 当前位置未提前。
To get all elements in ArrayList
you should use following code 要获取
ArrayList
所有元素,应使用以下代码
while(st.hasMoreTokens()) {
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.