What is the easiest/best/most correct way to iterate through the characters of a string in Java?

前端 未结 15 1418
挽巷
挽巷 2020-11-22 11:14

StringTokenizer? Convert the String to a char[] and iterate over that? Something else?

15条回答
  •  遥遥无期
    2020-11-22 11:35

    See The Java Tutorials: Strings.

    public class StringDemo {
        public static void main(String[] args) {
            String palindrome = "Dot saw I was Tod";
            int len = palindrome.length();
            char[] tempCharArray = new char[len];
            char[] charArray = new char[len];
    
            // put original string in an array of chars
            for (int i = 0; i < len; i++) {
                tempCharArray[i] = palindrome.charAt(i);
            } 
    
            // reverse array of chars
            for (int j = 0; j < len; j++) {
                charArray[j] = tempCharArray[len - 1 - j];
            }
    
            String reversePalindrome =  new String(charArray);
            System.out.println(reversePalindrome);
        }
    }
    

    Put the length into int len and use for loop.

提交回复
热议问题