给定一个字符串S、c1和c2。用c2替换字符c1,用c1替换字符c2。 例如:
null
Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul
我们在C++中有这个问题的解决方案,请参考 在字符串S中,用c2替换字符c1,用c1替换c2 链接我们将使用Python快速解决这个问题 Lambda表达式 和 地图() 作用我们将创建一个 lambda表达式 如果字符串中的字符c1将被c2替换,c2将被c1替换,其他字符将保持不变,那么我们将 地图 在字符串的每个字符上使用此表达式,并将得到更新的字符串。
# Function to replace a character c1 with c2 # and c2 with c1 in a string S def replaceChars( input ,c1,c2): # create lambda to replace c1 with c2, c2 # with c1 and other will remain same # expression will be like "lambda x: # x if (x!=c1 and x!=c2) else c1 if (x==c2) else c2" # and map it onto each character of string newChars = map ( lambda x: x if (x! = c1 and x! = c2) else c1 if (x = = c2) else c2, input ) # now join each character without space # to print resultant string print (''.join(newChars)) # Driver program if __name__ = = "__main__" : input = 'grrksfoegrrks' c1 = 'e' c2 = 'r' replaceChars( input ,c1,c2) |
输出:
geeksforgeeks
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END