可以使用栈来解决这个问题。遍历字符串的每个字符,当遇到左括号时,将该字符入栈;当遇到右括号时,将栈顶的元素弹出,直到栈顶元素为左括号。这样可以保证在嵌套字符串中的空格不会被拆分。
以下是一个示例代码:
def split_string(s):
stack = []
result = []
start = 0
for i in range(len(s)):
if s[i] == ' ' and len(stack) == 0:
result.append(s[start:i])
start = i + 1
elif s[i] == '(':
stack.append('(')
elif s[i] == ')' and stack[-1] == '(':
stack.pop()
elif i == len(s) - 1:
result.append(s[start:])
return result
这个函数会返回按空格拆分后的字符串列表。例如,对于输入字符串 "hello world (nested string)",函数的返回结果为 ['hello', 'world', '(nested string)']。
下一篇:按空格拆分字符串,需要澄清。