Java 如何将 for-each 循环应用于字符串中的每个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2451650/
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 do I apply the for-each loop to every character in a String?
提问by Lyndon White
So I want to iterate for each character in a string.
所以我想对字符串中的每个字符进行迭代。
So I thought:
所以我认为:
for (char c : "xyz")
but I get a compiler error:
但我收到一个编译器错误:
MyClass.java:20: foreach not applicable to expression type
How can I do this?
我怎样才能做到这一点?
采纳答案by polygenelubricants
The easiest way to for-each every char
in a String
is to use toCharArray()
:
for-each char
in a的最简单方法String
是使用toCharArray()
:
for (char ch: "xyz".toCharArray()) {
}
This gives you the conciseness of for-each construct, but unfortunately String
(which is immutable) must perform a defensive copy to generate the char[]
(which is mutable), so there is some cost penalty.
这为您提供了 for-each 构造的简洁性,但不幸的是String
(这是不可变的)必须执行防御性副本来生成char[]
(这是可变的),因此存在一些成本损失。
From the documentation:
从文档:
[
toCharArray()
returns] a newly allocated character arraywhose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
[
toCharArray()
返回]一个新分配的字符数组,其长度为该字符串的长度,其内容被初始化为包含该字符串所代表的字符序列。
There are more verbose ways of iterating over characters in an array (regular for loop, CharacterIterator
, etc) but if you're willing to pay the cost toCharArray()
for-each is the most concise.
迭代数组中的字符有更详细的方法(常规 for 循环CharacterIterator
、 等),但如果您愿意toCharArray()
为每个字符付费,则是最简洁的方法。
回答by Matthew Flaschen
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
回答by codaddict
You need to convert the String object into an array of char using the toCharArray
() method of the String class:
您需要使用toCharArray
String 类的() 方法将 String 对象转换为 char 数组:
String str = "xyz";
char arr[] = str.toCharArray(); // convert the String object to array of char
// iterate over the array using the for-each loop.
for(char c: arr){
System.out.println(c);
}
回答by user1690439
For Travers an String you can also use charAt()
with the string.
对于 Travers an String,您也可以charAt()
与字符串一起使用。
like :
喜欢 :
String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element
System.out.println(st); // print the char at 0 index
charAt()
is method of string handling in java which help to Travers the string for specific character.
charAt()
是java中的字符串处理方法,有助于遍历特定字符的字符串。
回答by kyxap
Another useful solution, you can work with this string as array of String
另一个有用的解决方案,您可以将此字符串用作字符串数组
for (String s : "xyz".split("")) {
System.out.println(s);
}
回答by Donald Raab
If you use Java 8, you can use chars()
on a String
to get a Stream
of characters, but you will need to cast the int
back to a char
as chars()
returns an IntStream
.
如果您使用 Java 8,则可以使用chars()
on aString
来获取 aStream
字符,但您需要将其转换int
回 achar
作为chars()
返回 an IntStream
。
"xyz".chars().forEach(i -> System.out.print((char)i));
If you use Java 8 with Eclipse Collections, you can use the CharAdapter
class forEach
method with a lambda or method reference to iterate over all of the characters in a String
.
如果您将 Java 8 与Eclipse Collections 一起使用,您可以使用带有 lambda 或方法引用的CharAdapter
类forEach
方法来迭代String
.
Strings.asChars("xyz").forEach(c -> System.out.print(c));
This particular example could also use a method reference.
这个特定的例子也可以使用方法引用。
Strings.asChars("xyz").forEach(System.out::print)
Note: I am a committer for Eclipse Collections.
注意:我是 Eclipse Collections 的提交者。
回答by ander4y748
You can also use a lambda in this case.
在这种情况下,您也可以使用 lambda。
String s = "xyz";
IntStream.range(0, s.length()).forEach(i -> {
char c = s.charAt(i);
});
回答by akhil_mittal
In Java 8we can solve it as:
在Java 8 中,我们可以将其解决为:
String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
The method chars() returns an IntStream
as mentioned in doc:
方法 chars() 返回doc 中IntStream
提到的一个:
Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.
返回一个 int 流,零扩展此序列中的 char 值。映射到代理代码点的任何字符都未经解释地传递。如果在读取流时序列发生变异,则结果未定义。
Why use forEachOrdered
and not forEach
?
为什么使用forEachOrdered
而不是forEach
?
The behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the streamif the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept. Also check this questionfor more.
的行为forEach
是明确地不确定性,其中作为forEachOrdered
执行用于该流的每个元件的操作,在该流的遭遇顺序如果流具有规定的遭遇顺序。所以forEach
不保证订单会被保留。另请查看此问题以获取更多信息。
We could also use codePoints()
to print, see this answerfor more details.
我们也可以codePoints()
用于打印,有关更多详细信息,请参阅此答案。
回答by Ossifer
Unfortunately Java does not make String
implement Iterable<Character>
. This could easily be done. There is StringCharacterIterator
but that doesn't even implement Iterator
... So make your own:
不幸的是,Java 没有String
实现Iterable<Character>
。这很容易做到。有,StringCharacterIterator
但它甚至没有实现Iterator
......所以制作你自己的:
public class CharSequenceCharacterIterable implements Iterable<Character> {
private CharSequence cs;
public CharSequenceCharacterIterable(CharSequence cs) {
this.cs = cs;
}
@Override
public Iterator<Character> iterator() {
return new Iterator<Character>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < cs.length();
}
@Override
public Character next() {
return cs.charAt(index++);
}
};
}
}
Now you can (somewhat) easily run for (char c : new CharSequenceCharacterIterable("xyz"))
...
现在你可以(有点)轻松地运行for (char c : new CharSequenceCharacterIterable("xyz"))
......