Java 迭代拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23780057/
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
Iterating over split string
提问by Mika
After looking for a while, it's still bugging me:
找了好久,还是很困扰:
I have a simple code where I want to retrieve data looking like:
我有一个简单的代码,我想在其中检索如下所示的数据:
data1/data2/style…
and I want to separate the data at each /
. So I have written:
我想在每个/
. 所以我写了:
MyData = data.split("/")
and then:
进而:
for (i = 0; i < myData.size; i++)
to iterate over the values. But I'm getting the following error:
迭代这些值。但我收到以下错误:
no signature of method length for type argument: () values: []
so I'm assuming that myData
is empty.
所以我假设那myData
是空的。
回答by zmo
if you want to iterate using an integer, you should use MyData.size()
in the for loop.
如果要使用整数进行迭代,则应MyData.size()
在 for 循环中使用。
But it is a better idea to do:
但最好这样做:
String[] myData = data.split("/");
for (String s: myData) {
System.out.println(s);
}
to use each string of the array.
使用数组的每个字符串。
If the iteration only iterates once over your array, then it may be your string that has a problem. As a double check, you may do:
如果迭代仅在您的数组上迭代一次,则可能是您的字符串有问题。作为仔细检查,您可以执行以下操作:
System.out.println(myData.size());
You may also want to add a breakpoint after the .split()
and look using a debugger if the array really contains all the strings you're expecting it to contain.
.split()
如果数组确实包含您希望它包含的所有字符串,您可能还想在 之后添加一个断点并使用调试器查看。
回答by NickJ
I am having some trouble understanding your question, even with the translation :)
我在理解您的问题时遇到了一些麻烦,即使有翻译:)
In the line
在行中
mesDonnees = maDonnee.split("/");
mesDonnees
needs to be a String array (String[]) and you can loop through it like:
mesDonnees
需要是一个字符串数组 (String[]),你可以像这样循环遍历它:
for (String str : mesDonnees) {
//... do somwething with str
}
You can rename str
something in French if you like, I couldn't think of a suitable name
str
如果你愿意,你可以用法语重命名一些东西,我想不出合适的名字