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

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

问题描述

所以我想对字符串中的每个字符进行迭代.

So I want to iterate for each character in a string.

所以我想:

for (char c : "xyz")

但我收到编译器错误:

MyClass.java:20: foreach not applicable to expression type

我该怎么做?

推荐答案

String 中的每个 char 进行 for-each 的最简单方法是使用 toCharArray():

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

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

这为您提供了 for-each 结构的简洁性,但不幸的是 String(它是不可变的)必须执行防御性复制以生成 char[](它是可变),所以会有一些成本损失.

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.

来自文档:

[toCharArray() 返回] 一个新分配的字符数组,其长度为该字符串的长度,其内容被初始化为包含该字符串所代表的字符序列.

[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.

迭代数组中的字符有更详细的方法(常规 for 循环、CharacterIterator 等)但如果您愿意支付成本 toCharArray() for-each 是最简洁的.

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天全站免登陆