Problem replacing char in char array with a digit

186 Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER
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.

2
On

The character '1' has a different value from the number 1.

You can change

char p = 1;

to

char p = '1';

and I think that will give you what you want, as long you're not trying to insert more than 9 numbers in your string. Otherwise you'll need to cope with inserting extra digits, which you cannot do into a char-array, because it has a fixed length.

0
On

the root of the problem is already in the comments,

in java the types make a difference in memory size and its representation

int x = 1; and char y = '1'

are not holding the same value, this is because many numerical representations are related with ascii codes and the value you have to assing to y to get the number 1 printed is HEX 0x31 or DEC 49.

take a look at the ascci table

enter image description here