0

I need this program to replace all r's with h's if they follow a vowel. This is just a test program, my actual assignment is to replace all the r's in the "Jaws" script with h's that follow a vowel, and do other various task to that string.

    public static void main(String[] args) {
        String s = "Hey, I'm from boston. harbor, fotter, slobber, murder.";
        System.out.println(replace(s));

    }

    //this method should replace r with h if it follows a vowel.
    public static String replace(String s) {
        String newS = "";
        String vowels ="aeiouAEIOU";
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == 'r' && isVowel(s.charAt(i-1))) {
                newS = s.replace("r", "h");
            }   
        }
        return newS;
    }
    //this method will check if a character is a vowel or not.
    public static Boolean isVowel(char s) {
        String vowels="aeiouAEIOU";
        if (vowels.contains("" + s)) {
            return true;
        }
        return false;
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    What does your code produce instead of what expected output, have you debugged your code using breakpoints and / or System.out.println-Statements? – luk2302 Oct 23 '17 at 13:14
  • 1
    use a debugger to find out what is happening – Jens Oct 23 '17 at 13:15
  • `replace` will replace all occurrence instead of particular one – Pavneet_Singh Oct 23 '17 at 13:15
  • What @Pavneet_Singh means is that `newS = s.replace("r", "h")` will replace all occurrences of `"r"` by `"h"` as explained [here](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)). – Bernat Oct 23 '17 at 13:18
  • Sorry for forgetting to mention. My code currently replaces all r's with h's regardless of what character comes before them. I will try debugger. Is there a String.replace function that will only replace particular occurrences rather than all? – John Antonio Mancini Oct 23 '17 at 13:19
  • Your replace method should look like below public static String replace(String s) { String newS = "" + s.charAt(0); for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == 'r' && isVowel(s.charAt(i-1))) { newS = newS+"h"; } else newS = newS+s.charAt(i); } return newS; } – Zenith Oct 23 '17 at 13:46

1 Answers1

0

Please use String builder to replace at specific index as said Replace a character at a specific index in a string? Below how your replace method should look like

public static String replace(String s) {
StringBuilder myName = new StringBuilder(s);

for (int i = 1; i < s.length(); i++) {
  if (s.charAt(i) == 'r' && isVowel(s.charAt(i - 1))) {
    myName.setCharAt(i, 'h');

  }
}
return myName.toString();

}

shakeel
  • 1,609
  • 1
  • 14
  • 14