Write a function to replace all occurrence of a character with another character and vice versa in a string
Implement the function to modify and return the string ‘ str’ in such a way that all occurrences of ‘ch1’ in the original string are replaced by ‘ch2’ and all occurrences of ‘ch2’ in the original string are replaced by ‘ch1’.
Assumption: String Contains only lower-case alphabetical letters.
Note: Return null if the string is null or None.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static String replaceCharacters(String str,char ch1,char ch2){ if(str==null) return null; else{ String result = ""; for(int i=0; i<str.length; i++){ char ch = str.charAt(i); if(ch==ch1) result += ch2; else if(ch==ch2) result += ch1; else result += ch; } return result; } } |
Python
def replaceCharacters(str,ch1,ch2): if len(str) is None: return None else: result = "" for ch in str: if ch==ch1: result += ch2 elif ch==ch2: result += ch1 else: result += ch return result |