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

本文翻译自: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说:

StringTokenizer is 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 of String or the java.util.regex package 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 lenfor循环。


#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. 第一个可能更快,然后第二个可能更具可读性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值