如何对字符串中的每个字符应用for-each循环?

时间:2022-06-06 12:49:56

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?

我该怎么做呢?

8 个解决方案

#1


255  

The easiest way to for-each every char in a String is to use toCharArray():

对于字符串中的每个字符,最简单的方法是使用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 array whose 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.

在数组中迭代字符的方法比较冗长(循环的规则,特性迭代器等等),但是如果你愿意支付toCharArray()的代价,那么每个都是最简洁的。

#2


32  

String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

 

 

#3


6  

You need to convert the String object into an array of char using the toCharArray() method of the String class:

您需要使用String类的toCharArray()方法将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);
}

#4


3  

Another useful solution, you can work with this string as array of String

另一个有用的解决方案是,您可以使用这个字符串作为字符串数组

for (String s : "xyz".split("")) {
    System.out.println(s);
}

#5


2  

In Java 8 we 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.

返回从这个序列中扩展char值的int 0流。映射到代理代码点的任何字符都通过未解释的方式传递。如果在读取流时序列发生突变,则结果是未定义的。

Why use forEachOrdered and not 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 stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

forEach的行为是显式不确定性的,当forEachOrdered对流的每个元素执行操作时,如果流具有定义的遇到顺序,那么它的行为就是流的遇到顺序。所以forEach并不保证订单会被保留。还要检查这个问题。

We could also use codePoints() to print, see this answer for more details.

我们还可以使用codePoints()来打印,详细信息请参见此答案。

#6


1  

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()来获取字符流,但是需要将int类型转换回char,因为chars()返回一个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.

如果在Eclipse集合中使用Java 8,那么可以使用CharAdapter类forEach方法,并使用lambda或方法引用来迭代字符串中的所有字符。

CharAdapter.adapt("xyz").forEach(c -> System.out.print(c));

This particular example could also use a method reference.

这个特定的示例也可以使用方法引用。

CharAdapter.adapt("xyz").forEach(System.out::print)

Note: I am a committer for Eclipse Collections.

注意:我是Eclipse集合的提交者。

#7


0  

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);
    });

#8


-6  

For Travers an String you can also use charAt() with the 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中处理字符串的方法,它有助于为特定字符遍历字符串。

#1


255  

The easiest way to for-each every char in a String is to use toCharArray():

对于字符串中的每个字符,最简单的方法是使用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 array whose 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.

在数组中迭代字符的方法比较冗长(循环的规则,特性迭代器等等),但是如果你愿意支付toCharArray()的代价,那么每个都是最简洁的。

#2


32  

String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

 

 

#3


6  

You need to convert the String object into an array of char using the toCharArray() method of the String class:

您需要使用String类的toCharArray()方法将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);
}

#4


3  

Another useful solution, you can work with this string as array of String

另一个有用的解决方案是,您可以使用这个字符串作为字符串数组

for (String s : "xyz".split("")) {
    System.out.println(s);
}

#5


2  

In Java 8 we 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.

返回从这个序列中扩展char值的int 0流。映射到代理代码点的任何字符都通过未解释的方式传递。如果在读取流时序列发生突变,则结果是未定义的。

Why use forEachOrdered and not 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 stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

forEach的行为是显式不确定性的,当forEachOrdered对流的每个元素执行操作时,如果流具有定义的遇到顺序,那么它的行为就是流的遇到顺序。所以forEach并不保证订单会被保留。还要检查这个问题。

We could also use codePoints() to print, see this answer for more details.

我们还可以使用codePoints()来打印,详细信息请参见此答案。

#6


1  

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()来获取字符流,但是需要将int类型转换回char,因为chars()返回一个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.

如果在Eclipse集合中使用Java 8,那么可以使用CharAdapter类forEach方法,并使用lambda或方法引用来迭代字符串中的所有字符。

CharAdapter.adapt("xyz").forEach(c -> System.out.print(c));

This particular example could also use a method reference.

这个特定的示例也可以使用方法引用。

CharAdapter.adapt("xyz").forEach(System.out::print)

Note: I am a committer for Eclipse Collections.

注意:我是Eclipse集合的提交者。

#7


0  

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);
    });

#8


-6  

For Travers an String you can also use charAt() with the 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中处理字符串的方法,它有助于为特定字符遍历字符串。