Search code examples
javacharchararray

Problem replacing char in char array with a digit


Given a string, I have to replace all vowels with their respective position in the array. However, my code returns some strange symbols instead of numbers. Where's the problem?

        String s = "this is my string";
        char p = 1;
        char[] formatted = s.toCharArray();
        for(int i = 0; i < formatted.length; i++) {
            if(formatted[i] == 'a' ||formatted[i] == 'e' ||formatted[i] == 'i'
                    ||formatted[i] == 'o' ||formatted[i] == 'u') {
                formatted[i] = p;
            }
            p++;
        }
        s = String.valueOf(formatted);
        System.out.println(s);

P.S: Numbers are bigger than 10


Solution

  • this is my   s  t  r  i  n g
    012345678910 11 12 13 14
    

    The position of i in string is 14 but 14 is not a character; it's a numeric string. It means that you need to deal with strings instead of characters. Split s using "" as the delimiter, process the resulting array and finally join the array back into a string using "" as the delimiter.

    class Main {
        public static void main(String[] args) {
            String s = "this is my string";
            String[] formatted = s.split("");
            for (int i = 0; i < formatted.length; i++) {
                if (formatted[i].matches("(?i)[aeiou]")) {
                    formatted[i] = String.valueOf(i);
                }
            }
            s = String.join("", formatted);
            System.out.println(s);
        }
    }
    

    Output:

    th2s 5s my str14ng
    

    The regex, (?i)[aeiou] specifies case-insensitive match for one of the vowels where (?i) specifies the case-insensitiveness. Test it here.