Akshit Agarwal Akshit Agarwal - 1 year ago 103
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];
for (int i = 0; str[i] != '\0'; i++)
if (str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
cout << str;

Answer Source

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 ='_';
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download