Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use charAt or toCharArray? [closed]

Tags:

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

    }
like image 736
JavaDeveloper Avatar asked Mar 17 '14 00:03

JavaDeveloper


1 Answers

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?

like image 163
John Humphreys Avatar answered Sep 29 '22 04:09

John Humphreys