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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:09:36  来源:igfitidea点击:

How to iterate through a String

javastringloops

提问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 Strings 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.charactersOfreturns 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)); 
}