【发布时间】:2012-10-29 07:54:14
【问题描述】:
可能重复:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
我考虑的是时间和效率。考虑到这些,哪种方法(以下方法或其他未提及的方法)是遍历字符串每个字符的最有效方法?
String str = "Foo Bar";
for(int i=0;i<str.length();i++)
System.out.println(str.charAt(i)); // access the character using .charAt()
for(char letter: str.toCharArray)
System.out.println(letter); // use for-each loop with the char array.
同样,可能有更好的方法来做到这一点,但我也很好奇上述两者之间是否存在重大的时间/资源差异。
【问题讨论】:
-
严格来说,String 方法
.charAt()是 O(1) 并且可能比将字符串冗余转换为字符数组更快(因为字符串已经由 char 数组支持)