题解 | 参数解析
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
import sys
cmd = sys.stdin.read().strip()
def analysis(cmd):
current = []
res = []
pre_is_even = True # 标记遇到空格时前面是否有奇数个引号
for i in range(len(cmd)):
if cmd[i] == '"':
pre_is_even = not pre_is_even
elif cmd[i] == ' ' and pre_is_even:
res.append("".join(current))
current = []
else:
current.append(cmd[i])
if current:
res.append("".join(current))
return res
res = analysis(cmd)
print(len(res))
for s in res:
print(s)
使用收集器current,current只收集非空格和非引号,对字符串遍历:
1.使用in_quotes来判断是否在引号内,默认值为False,遇到引号后取not
2.当且仅当在引号外:遇到空格时,将收集器中的字符拼接为字符串,加入res
3.其他时候收集字符
4.读取到最后一位时:将收集器中的字符拼接,加入res
