参数解析

题目描述
在命令行输入如下命令:
xcopy /s c:\ d:\,
各个参数如下: 
参数1:命令字xcopy 
参数2:字符串/s
参数3:字符串c:\
参数4: 字符串d:\
请编写一个参数解析程序,实现将命令行各个参数解析出来。
 
解析规则: 
1.参数分隔符为空格 
2.对于用“”包含起来的参数,如果中间有空格,不能解析为多个参数。比如在命令行输入xcopy /s “C:\program files” “d:\”时,参数仍然是4个,第3个参数应该是字符串C:\program files,而不是C:\program,注意输出参数时,需要将“”去掉,引号不存在嵌套情况。
3.参数不定长 
4.输入由用例保证,不会出现不符合要求的输入 
 
 
输入描述:
输入一行字符串,可以有空格
输出描述:

输出参数个数,分解后的参数,每个参数都独占一行

思路一:

import java.util.ArrayList;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.nextLine();
            ArrayList<String> list = new ArrayList<>();
            int i = 0;
            while (i < str.length())
            {
                char ch = str.charAt(i);
                String tmp = "";
                if (ch == '"')
                {
                    i++;
                    while (i < str.length() && str.charAt(i) != '"')
                    {
                        tmp += str.charAt(i);
                        i++;
                    }
                    i++;
                    list.add(tmp);
                    tmp = "";
                }
                else if (ch != ' ')
                {
                    while (i < str.length() && str.charAt(i) != ' ')
                    {
                        tmp += str.charAt(i);
                        i++;
                    }
                    i++;
                    list.add(tmp);
                    tmp = "";
                }
            }
            System.out.println(list.size());
            for (int j = 0; j < list.size(); j++)
                System.out.println(list.get(j));
        }
    }
}

思路二:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.nextLine();
            StringBuffer sb = new StringBuffer();
            int count = 0;
            int quota = 0;
            for (int i = 0; i < str.length(); i++)
            {
                if (str.charAt(i) == '\"')
                    quota++;
                else if (str.charAt(i) != ' ')
                    sb.append(str.charAt(i));
                else if (quota % 2 == 0)
                {
                    sb.append('\n');
                    count++;
                }
                else 
                    sb.append(' ');
            }
            System.out.println(count + 1);
            System.out.println(sb.toString());
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值