本文翻译自:What is the easiest/best/most correct way to iterate through the characters of a string in Java?
StringTokenizer ? StringTokenizer ? Convert the String to a char[] and iterate over that? 将String转换为char[]并对其进行迭代? Something else? 还有吗
#1楼
参考:https://stackoom.com/question/pCg/在Java中迭代字符串的字符最简单-最佳-最正确的方法是什么
#2楼
I use a for loop to iterate the string and use charAt() to get each character to examine it. 我使用for循环来迭代字符串,并使用charAt()来获取每个字符以进行检查。 Since the String is implemented with an array, the charAt() method is a constant time operation. 由于String是通过数组实现的,因此charAt()方法是恒定时间操作。
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. 这完全取决于您的个人风格。
#3楼
I wouldn't use StringTokenizer as it is one of classes in the JDK that's legacy. 我不会使用StringTokenizer因为它是JDK中的遗留类之一。
The javadoc says: Javadoc说:
StringTokenizeris a legacy class that is retained for compatibility reasons although its use is discouraged in new code.StringTokenizer是一个遗留类,出于兼容性原因而保留,尽管在新代码中不鼓励使用它。 It is recommended that anyone seeking this functionality use the split method ofStringor thejava.util.regexpackage instead. 建议任何寻求此功能的人改用String的split方法或java.util.regex包。
#4楼
See The Java Tutorials: Strings . 请参阅Java教程:字符串 。
public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] = palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray[j] = tempCharArray[len - 1 - j];
}
String reversePalindrome = new String(charArray);
System.out.println(reversePalindrome);
}
}
Put the length into int len and use for loop. 将长度放入int len并for循环。
#5楼
There are some dedicated classes for this: 为此有一些专用的类:
import java.text.*;
final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
// process c
...
}
#6楼
Two options 两种选择
for(int i = 0, n = s.length() ; i < n ; i++) {
char c = s.charAt(i);
}
or 要么
for(char c : s.toCharArray()) {
// process c
}
The first is probably faster, then 2nd is probably more readable. 第一个可能更快,然后第二个可能更具可读性。
Java字符串迭代技巧
本文探讨了在Java中迭代字符串字符的多种方法,包括使用for循环和charAt()方法、StringTokenizer类、CharacterIterator类以及将字符串转换为char数组。讨论了各种方法的优缺点,如速度、可读性和正确性。
1432

被折叠的 条评论
为什么被折叠?



