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

查看:204
本文介绍了在Java中迭代字符串的字符的最简单/最好/最正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StringTokenizer ?将 String 转换为 char [] 并迭代?我使用一个for循环来迭代字符串并使用 charAt()

code>来获取每个字符来检查它。由于String是用数组实现的,所以 charAt()方法是一个常量时间操作。

  String s =... stuff ...; 

for(int i = 0; i char c = s.charAt(i);
//进程char
}

对我来说似乎是最容易的。



至于正确性,我不相信这里存在。这都是基于你的个人风格。


StringTokenizer? Convert the String to a char[] and iterate over that? Something else?

解决方案

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