基于包裹元素的引号字符实现数组元素合并转换
这个问题挺常见的——处理被拆分的带引号字符串数组,我来分享几个实用的实现思路,用Python代码举例说明,你可以直接参考适配到自己的语言里:
核心思路:状态追踪法
核心逻辑就是用一个状态变量记录当前是否处于「待拼接」模式,遍历数组时动态判断是直接存入结果,还是继续拼接片段:
- 初始化变量:创建结果数组
converted_array,再用两个临时变量:current_chunk(存储正在拼接的字符串片段)和active_quote(记录当前追踪的引号类型,单引号'或双引号"),初始都设为None。 - 逐个处理数组元素:
- 如果
current_chunk是None(当前没有待拼接的片段):- 检查当前元素是否以引号开头:
- 是:记录引号类型,把元素去掉开头引号后存入
current_chunk,进入待拼接状态。 - 否:直接把元素加入结果数组。
- 是:记录引号类型,把元素去掉开头引号后存入
- 检查当前元素是否以引号开头:
- 如果
current_chunk不为None(处于待拼接状态):- 检查当前元素是否以对应的引号结尾:
- 是:把
current_chunk和当前元素去掉结尾引号的部分合并,存入结果数组,然后重置临时变量,退出待拼接状态。 - 否:把当前元素直接追加到
current_chunk后面,继续等待下一个元素。
- 是:把
- 检查当前元素是否以对应的引号结尾:
- 如果
- 边界处理:遍历结束后如果
current_chunk还不为None,说明存在未闭合的引号,可以根据需求选择保留片段、丢弃或者抛出提示。
代码实现(Python)
def merge_split_quotes(arr): converted = [] current_chunk = None active_quote = None for item in arr: if current_chunk is None: # 检查元素是否以引号开头 if len(item) > 0 and item[0] in ('"', "'"): active_quote = item[0] current_chunk = item[1:] # 移除开头引号 else: converted.append(item) else: # 检查元素是否以对应的引号结尾 if len(item) > 0 and item[-1] == active_quote: # 合并完整字符串并移除结尾引号 full_string = current_chunk + item[:-1] converted.append(full_string) current_chunk = None active_quote = None else: # 继续拼接片段 current_chunk += item # 处理未闭合的引号片段(可选逻辑) if current_chunk is not None: converted.append(f"{active_quote}{current_chunk}") return converted # 测试第一个示例 test_arr1 = ['"nam', 'e"', '"numb', 'er"'] print(merge_split_quotes(test_arr1)) # 输出: ['name', 'number'] # 测试第二个示例 test_arr2 = ["'name", "e'", "something", "'numb", "er'"] print(merge_split_quotes(test_arr2)) # 输出: ['name', 'something', 'number']
扩展思路:迭代器遍历法
如果觉得状态变量的逻辑有点绕,可以用迭代器来遍历数组,遇到需要拼接的元素时,主动取下一个元素继续合并,逻辑更直观:
def merge_split_quotes_iterator(arr): converted = [] arr_iter = iter(arr) for item in arr_iter: if item.startswith(('"', "'")): quote = item[0] current = item[1:] # 循环取下一个元素,直到找到闭合引号 while True: try: next_item = next(arr_iter) if next_item.endswith(quote): current += next_item[:-1] converted.append(current) break else: current += next_item except StopIteration: # 遍历完数组仍未找到闭合引号,处理未完成片段 converted.append(f"{quote}{current}") break else: converted.append(item) return converted
如果需要处理转义引号(比如"he said \"hello\""被拆分的情况),可以用正则表达式来判断开头/结尾的引号是否是未转义的,比如用r'^(?<!\\)"'匹配未转义的开头双引号,r'"(?!\\)$'匹配未转义的结尾双引号,适配更复杂的场景。
内容的提问来源于stack exchange,提问作者SaboSuke
相关产品推荐
相关产品推荐

