Java 如何遍历字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3799130/
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 to iterate through a String
提问by muttley91
How can I iterate through a string in Java?
如何遍历 Java 中的字符串?
I'm trying to use a foreach style for loop
我正在尝试使用 foreach 样式进行循环
for (char x : examplestring) {
//action
}
采纳答案by surajz
If you want to use enhanced loop, you can convert the string to charArray
如果要使用增强循环,可以将字符串转换为charArray
for (char ch : exampleString.toCharArray()) {
System.out.println(ch);
}
回答by cletus
Java String
s aren't character Iterable
. You'll need:
JavaString
不是 character Iterable
。你需要:
for (int i = 0; i < examplestring.length(); i++) {
char c = examplestring.charAt(i);
...
}
Awkward I know.
尴尬我知道。
回答by ColinD
Using Guava(r07) you can do this:
使用Guava(r07) 你可以这样做:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while notcopying the string to a new array. Lists.charactersOf
returns a viewof the string as a List
.
这具有使用 foreach 的便利,而不是将字符串复制到新数组。Lists.charactersOf
将字符串的视图作为 a返回List
。
回答by Dead Programmer
How about this
这个怎么样
for (int i = 0; i < str.length(); i++) {
System.out.println(str.substring(i, i + 1));
}