如何将for-each循环应用于字符串中的每个字符? [英] How do I apply the for-each loop to every character in a String?

查看:880
本文介绍了如何将for-each循环应用于字符串中的每个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想迭代字符串中的每个字符。



所以我想:

  for(char c:xyz)

编译器错误:

  MyClass.java:20:foreach不适用于表达式类型



我如何做到这一点?

解决方案

String 中每个 char 的最简单的方法是使用 toCharArray / code>:

  for(char ch:xyz.toCharArray()){
}

这给出了for-each结构的简洁性,但不幸的是 String (这是不可变的)必须执行防御复制以生成 char [] (这是可变的),因此有一些成本惩罚。 p>

文档


[ toCharArray c $ c>返回] 新分配的字符数组,其长度为该字符串的长度,其内容初始化为包含此字符串表示的字符序列。


对数组中的字符进行迭代的更多冗长方式(对于循环, CharacterIterator 等)你愿意支付成本 toCharArray() for-each是最简洁的。


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?

解决方案

The easiest way to for-each every char in a String is to use 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.

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.

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-each循环应用于字符串中的每个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆