在Java中遍历字符串字符的最简单/最好/最正确的方法是什么? [英] What is the easiest/best/most correct way to iterate through the characters of a string in Java?

查看:23
本文介绍了在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.

这篇关于在Java中遍历字符串字符的最简单/最好/最正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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