26

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);
       }

    }
Zhedar
  • 3,480
  • 1
  • 21
  • 44
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • 1
    If it's only for iterating over the characters, use `charAt(int)` (or ideally `codePointAt(int)`. – Sotirios Delimanolis Mar 17 '14 at 00:39
  • possible duplicate of [What is the easiest/best/most correct way to iterate through the characters of a string in Java?](http://stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a) – Sotirios Delimanolis Mar 17 '14 at 00:46
  • The real question is "what are you trying to do" ... there may be other things you would do with the different characters in the string. – ErstwhileIII Mar 17 '14 at 00:47
  • 3
    My observation, having actually worked on the implementation of charAt and array indexing, is that the main difference between the two is that you have (if not inlined by the JITC) a method call per character with charAt and only one method call per String with array indexing. Unless you were processing a lot of characters in each String, or performance was *very* critical, I'd go with charAt for simplicity. – Hot Licks Mar 17 '14 at 01:24
  • 2
    toCharArray performs better than charAt - https://leetcode.com/discuss/77851/java-15ms-easiest-solution-100-00%25 – Pradeep Apr 23 '16 at 18:38
  • 1
    When I did a problem on leetcode, it seems using *toCharArray* is twice as fast. Anybody know why? – Gengar Oct 08 '19 at 12:37

1 Answers1

15

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?

Community
  • 1
  • 1
John Humphreys
  • 37,047
  • 37
  • 155
  • 255