在Java中遍历字符串字符的最简单/最好/最正确的方法是什么?

2022-01-24 00:00:00 string iteration tokenize character java

在 Java 中遍历字符串字符的一些方法是:

Some ways to iterate through the characters of a string in Java are:

  1. 使用 StringTokenizer?
  2. String 转换为 char[] 并对其进行迭代.
  1. Using StringTokenizer?
  2. Converting the String to a char[] and iterating over that.

最简单/最好/最正确的迭代方式是什么?

What is the easiest/best/most correct way to iterate?

推荐答案

我使用 for 循环迭代字符串并使用 charAt() 获取每个字符来检查它.由于 String 是用数组实现的,所以 charAt() 方法是一个常数时间的操作.

I use a for loop to iterate the string and use charAt() to get each character to examine it. Since the String is implemented with an array, the charAt() method is a constant time operation.

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

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

这就是我会做的.这对我来说似乎是最简单的.

That's what I would do. It seems the easiest to me.

就正确性而言,我认为这里不存在.这完全取决于您的个人风格.

As far as correctness goes, I don't believe that exists here. It is all based on your personal style.

相关文章