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
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);
}
}
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:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With