Google Interview Question

Find out all special character in a string and replace it with another character

Interview Answer

Anonymous

Nov 1, 2016

public static void main(String[] args){ String mystring = "Hey my mom said. that I will not eat food. unless it is cooked well"; System.out.println("Original Sentence: " + mystring); mystring = replace(mystring, '.', ','); System.out.println("New Sentence: " + mystring); } public static String replace(String string, char toReplace, char replaceWith){ for (int i = 0; i < string.length(); i++) { if(string.charAt(i) == toReplace) { string = string.substring(0, i) + replaceWith + string.substring(i+1); } } return string; }