Warm tip: This article is reproduced from serverfault.com, please click

其他-在Java中迭代字符串的字符最简单/最好/最正确的方法是什么?

(其他 - What is the easiest/best/most correct way to iterate through the characters of a string in Java?)

发布于 2008-10-13 06:10:15

StringTokenizer将转换Stringchar[]并对其进行迭代?还有别的吗

Questioner
Paul Wicks
Viewed
0
4,211 2016-02-15 13:15:33

我使用for循环来迭代字符串,并使用它charAt()来获取每个字符以进行检查。由于String是通过数组实现的,因此该charAt()方法是恒定时间操作。

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    //Process char
}

那就是我会做的。在我看来,这是最简单的。

就正确性而言,我不认为这是存在的。这一切都取决于你的个人风格。