1

I'm having trouble writing down the code for this function.

Replacing the consonants

/** Return a string that is s but with all lowercase consonants (letters of
 * the English alphabet other than the vowels a, e, i, o, u) replaced with
 * _, and all uppercase consonants replaced with ^.
 *
 * Examples: For s = "Minecraft" return "^i_e__a__".
 *           For s = "Alan Turing" return "A_a_ ^u_i__".

This is what I have done so far:

String consonants = "bcdfghjklmnpqrstvwxyz";
for(int j = 0; j < consonants.length(); j++ ){
    int start = 0;
    if s.charAt(start) == consonants( I am unsure to tell it to look through the string I made)
        s.charAt(start).replace(s.substring(start,1), ("_"));
        if s.charAt(start) == s.substring(start,start+1).ToUpperCase(){
            s.charAt(start) = "'";
        }
    }
}
jww
  • 97,681
  • 90
  • 411
  • 885
Steve
  • 65
  • 1
  • 6
  • Possible duplicate of [Replace a character at a specific index in a string?](http://stackoverflow.com/questions/6952363/java-replace-a-character-at-a-specific-index-in-a-string) – jww Feb 16 '15 at 03:01

2 Answers2

3

You could use negative lookahead based regex or you need to manually write all the consonants.

String s = "Minecraft";
String m = s.replaceAll("(?![aeiouAEIOU])[a-z]", "_").replaceAll("(?![aeiouAEIOU])[A-Z]", "^");
System.out.println(m);

Output:

^i_e__a__
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • What do you get for "Braaaains"? – user253751 Feb 16 '15 at 03:03
  • This works, I was also wondering how to make it work using a for loop. would there have to be if statements for in case the s string is a capital letter? or would i use the built in function replace? – Steve Feb 16 '15 at 03:21
-2
String myName = "domanokz";
myName.charAt(4) = 'x';

If that's not what you're looking for:

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);
657784512
  • 613
  • 7
  • 14