如何基于靠近字符串中心的空格拆分长字符串为两个子串?
基于字符串中心附近的空格拆分字符串
给定目标字符串:
str_0 = "This is a very long string that I would like to split into two shorter strings"
完全可以基于靠近字符串中心的空格将其拆分为两个子串,最终能得到你预期的结果:
str_1 = "This is a very long string that I would" str_2 = "like to split into two shorter strings"
实现思路与代码(Python示例)
核心逻辑是找到距离字符串中心最近的空格位置,以此为拆分点分割字符串:
- 计算字符串的中心索引位置
- 分别在中心索引的左侧、右侧查找最近的空格
- 比较两个空格到中心的距离,选择更近的作为拆分点(若某侧无空格则直接用另一侧的)
- 基于拆分点切割字符串,去除可能的首尾空格
str_0 = "This is a very long string that I would like to split into two shorter strings" # 计算字符串中心位置 center_idx = len(str_0) // 2 # 查找中心左侧最近的空格 left_split = str_0.rfind(' ', 0, center_idx) # 查找中心右侧最近的空格 right_split = str_0.find(' ', center_idx) # 确定最终拆分点 if left_split == -1: split_pos = right_split elif right_split == -1: split_pos = left_split else: # 选离中心更近的空格 split_pos = left_split if (center_idx - left_split) <= (right_split - center_idx) else right_split # 执行拆分并清理多余空格 str_1 = str_0[:split_pos].strip() str_2 = str_0[split_pos+1:].strip() # 输出结果 print(f"str_1 = {repr(str_1)}") print(f"str_2 = {repr(str_2)}")
运行这段代码后,输出结果完全符合预期。这种方法也适用于其他类似的长字符串拆分场景,能保证两个子串的长度尽可能接近。
内容的提问来源于stack exchange,提问作者Adrien Amour
相关产品推荐
相关产品推荐

