如何在字符串替换中循环交替使用两个替换字符
实现交替字符替换的方案
这是个挺有意思的需求!核心思路很明确:遍历字符串时跟踪目标字符的出现次数,每遇到一个目标字符,就根据次数的奇偶性选择对应的替换符号(奇数位用第一个替换符,偶数位用第二个),非目标字符直接保留。
Python 实现
这种方式用列表收集结果(比直接字符串拼接更高效),逻辑清晰易懂:
def alternate_replace(original_str, target_char, replace1, replace2): target_count = 0 result_chars = [] for char in original_str: if char == target_char: target_count += 1 # 奇数位置用replace1,偶数用replace2 result_chars.append(replace1 if target_count % 2 == 1 else replace2) else: result_chars.append(char) return ''.join(result_chars) # 测试示例 test_string = "hello...." output = alternate_replace(test_string, ".", "!", "?") print(output) # 输出:hello!?!?
JavaScript 实现
如果是前端场景,用JavaScript的实现逻辑和Python几乎一致:
function alternateReplace(originalStr, targetChar, replace1, replace2) { let targetCount = 0; const resultChars = []; for (const char of originalStr) { if (char === targetChar) { targetCount++; resultChars.push(targetCount % 2 === 1 ? replace1 : replace2); } else { resultChars.push(char); } } return resultChars.join(''); } // 测试 const testStr = "hello...."; const output = alternateReplace(testStr, ".", "!", "?"); console.log(output); // 输出:hello!?!?
额外说明
- 这种遍历的方式不需要处理正则转义问题,哪怕目标字符是
*、+这类正则元字符也能正常工作,通用性更强。 - 计数是全局的,也就是整个字符串中所有目标字符按出现顺序依次计数,完全符合你给出的示例要求。
内容的提问来源于stack exchange,提问作者S_R
相关产品推荐
相关产品推荐

