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
The position of
i
instring
is14
but14
is not a character; it's a numeric string. It means that you need to deal with strings instead of characters. Splits
using""
as the delimiter, process the resulting array and finally join the array back into a string using""
as the delimiter.Output:
The regex,
(?i)[aeiou]
specifies case-insensitive match for one of the vowels where(?i)
specifies the case-insensitiveness. Test it here.