Java 我应该使用 charAt 还是 toCharArray?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22445104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I use charAt or toCharArray?
提问by JavaDeveloper
Which of the following options is considered a good practice to loop through the String
?
Should we use charAt
or convert to a char array ? I am looking for answers in all terms including performance and space used
以下哪个选项被认为是循环遍历的好习惯String
?
我们应该使用charAt
还是转换为字符数组?我正在寻找所有方面的答案,包括性能和使用的空间
public static void doChose (String str) {
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
// vs
char[] chars = str.toCharArray();
for (char c : chars) {
System.out.println(c);
}
}
采纳答案by John Humphreys - w00te
It's all personal preference at this point I think :) but looping through and using charAt(i) would be the most common way of handling this. This question covers it fine:
在这一点上,我认为这完全是个人喜好:) 但循环使用 charAt(i) 将是处理这个问题的最常见方法。这个问题很好地涵盖了它:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?