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;
    }
}
6
  • 1
    What does your code produce instead of what expected output, have you debugged your code using breakpoints and / or System.out.println-Statements? Commented Oct 23, 2017 at 13:14
  • 1
    use a debugger to find out what is happening Commented Oct 23, 2017 at 13:15
  • replace will replace all occurrence instead of particular one Commented Oct 23, 2017 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. Commented Oct 23, 2017 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? Commented Oct 23, 2017 at 13:19

1 Answer 1

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();

}

Sign up to request clarification or add additional context in comments.

2 Comments

This worked, thanks!
@John Antonio please accept it as answer. Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.