在命令行输入如下命令:
xcopy /s c:\\ d:\\e,
各个参数如下:
参数1:命令字xcopy
参数2:字符串/s
参数3:字符串c:\\
参数4: 字符串d:\\e
请编写一个参数解析程序,实现将命令行各个参数解析出来。
解析规则:
1.参数分隔符为空格
2.对于用""包含起来的参数,如果中间有空格,不能解析为多个参数。比如在命令行输入xcopy /s "C:\\program files" "d:\"时,参数仍然是4个,第3个参数应该是字符串C:\\program files,而不是C:\\program,注意输出参数时,需要将""去掉,引号不存在嵌套情况。
3.参数不定长
4.输入由用例保证,不会出现不符合要求的输入
数据范围:字符串长度:1\le s\le 1000\1≤s≤1000 
进阶:时间复杂度:O(n)\O(n) ,空间复杂度:O(n)\O(n) 
输入描述:输入一行字符串,可以有空格
输出描述:输出参数个数,分解后的参数,每个参数都独占一行
输入:
xcopy /s c:\\ d:\\e
输出:
4
xcopy
/s
c:\\
d:\\e
运行时间:41ms
超过100.00% 用Python 3提交的代码
占用内存:4668KB
超过15.79%用Python 3提交的代码
def exam(instr):
    lis = instr.split(' ')
    # print(lis)
    res = []
    temp = ''
    cnt = 0
    for i in lis:
        # 分裂的list,单个i,没有引号也没有\\且引号统计cnt不为1
        if '"' not in i and '\\' in i and cnt != 1:
            # res.append(i.replace('\\\\',"\\"))
            # 字符串存储的是\\\\,但实际上print打印会自动转义,即去掉2个\\
            res.append(i)
            # 单个list-i处理完毕后直接continue,不需要继续下一个if判断
            continue
        if '"' not in i and cnt != 1:
            # 引号统计不是1个,则说明不是引号中间因空格切片的数字
            res.append(i)
        if '"' not in i and cnt == 1:
            # 引号不在i,但是计数cnt引号却为1,说明该list-i值为引号内的内容
            temp += ' ' + i + ' '
            continue
        if '"' == i[-1] and '"' == i[0]:
            # 1个list里面有2个引号,则为闭环字符串
            temp += i[1:-1]
            # res.append(temp.replace('\\\\',"\\"))
            res.append(temp)
            temp = ''
            continue
        # cnt开始计数,刚遇到第一个或成对后的第一个左引号
        if '"' == i[0]:
            temp += i[1:]
            cnt += 1
        # 遇到第二个引号,则写入结果list
        if '"' == i[-1] and cnt == 1:
            temp += ' ' + i[0:-1]
            cnt = 0
            # res.append(temp.replace('\\\\','\\'))
            res.append(temp)
            temp = ''

    print(len(res))
    for i in res:
        print(i.replace('  ',' '))
        

instr = input().strip()
exam(instr=instr)