Akshit Agarwal Akshit Agarwal - 1 month ago 6
Java Question

How to do this in Java?

I have written a piece of code in C++.
How to do this thing up in Java?
I have been trying to learn Java and got stuck up doing this.
Sorry for such a basic question.
Thanks anyway.

void convertstring()
{
char str[100];
gets(str);
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
str[i]='_';
}
cout << str;
}

Answer

Java has immutable Strings, so one cannot in-place alter a String. Also java string are not terminated by a '\0' - which is a normal char in java.

String convertString(String str) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
           ch ='_';
        sb.append(ch);
    }
    return sb.toString();
}

String s = convertString("hello world!");
s = convertString(s);
System.out.println(s); // "h_ll_ w_rld!"

Also note that any call with a variable as parameter does not assign to/overwrite that variable.