首页 > 试题广场 >

参数解析

[编程题]参数解析
  • 热度指数:174977 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

在命令行输入如下命令:

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

输入

xcopy /s c:\\ d:\\e

输出

4
xcopy
/s
c:\\
d:\\e
第一种想法:根据正则匹配空格(排除双引号中空格),按此正则分割字符串求解;第二种想法:直接按照空格分割字符串,再将有双引号的字符串命令拼接回来。
方法一:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s=in.nextLine();
        String[] str = s.split("(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)\\s+");
        System.out.println(str.length);
        for (String t : str) {
            if(t.charAt(0)=='"'){
                t=t.substring(1,t.length()-1);
            }
            System.out.println(t);
        }
    }
}
方法二:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s=in.nextLine();
        int n=0;
        String[] str = s.split("[ ]{1,}");
        boolean flag=false;
        for(int i=0;i<str.length;i++){
            if(flag){
                str[n-1]=str[n-1]+" "+str[i];
                if(str[i].charAt(str[i].length()-1)=='"'){
                    str[n-1]=str[n-1].substring(1,str[n-1].length()-1);
                    flag=false;
                }
            }else{
                str[n]=str[i];
                n++;
            }
            if(str[i].charAt(0)=='"'){
                if(str[i].charAt(str[i].length()-1)=='"'){
                    str[n-1]=str[i].substring(1,str[i].length()-1);
                }else{
                    flag=true;
                }
            }
        }
        System.out.println(n);
        for (int j=0;j<n;j++) {
            System.out.println(str[j]);
        }
    }
}



发表于 2025-05-01 14:17:32 回复(0)
//一个一个字符来就好了 注意字符串末尾加空格 才能输出最后一个参数
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.nextLine();
        StringBuilder b = new StringBuilder(a);
        b.append(" ");
        a = b.toString();
        List<String> c = new ArrayList<>();
        StringBuilder d = new StringBuilder();
        boolean x = false;
        for (char p : a.toCharArray()) {
            if(p=='\"'){
                x = !x;
            }else{
                if(!x){//在“之外
                    if (p == ' ') {
                        c.add(d.toString());
                        d.delete(0, d.length());
                    } else if (p == '\"') {
                        x = !x;
                    } else {
                        d.append(p);
                    }

                }else{//在”之内
                    if (p == '\"') {
                        x = !x;
                    } else {
                        d.append(p);
                    }
                }
            }
        }
        System.out.println(c.size());
        for(String y:c){
            System.out.println(y);
        }
    }
}

发表于 2025-03-29 15:37:38 回复(0)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        List<String> list = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            StringBuilder sb = new StringBuilder();
            //不是空格就继续遍历
            while (i < s.length() && s.charAt(i) != ' ') {
                //如果是开始双引号,需要找到结束双引号
                if (s.charAt(i) == '"') {
                    //双引号不加到字符串中,所以移动到下一个字符
                    i++;
                    //只要不是结束双引号,就继续遍历
                    while (s.charAt(i) != '"') {
                        sb.append(s.charAt(i));
                        i++;
                    }
                } else {
                    //不是双引号就加到字符串里
                    sb.append(s.charAt(i));
                }
                i++;
            }
            //遇到空格且有参数,则保存
            if (sb.length() > 0) {
                list.add(sb.toString());
            }
        }

        System.out.println(list.size());
        for (String p : list) {
            System.out.println(p);
        }
        
    }
}

发表于 2025-02-21 22:39:59 回复(0)
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        ArrayList<String> list = new ArrayList<>();

        int i = 0;
        while (i < s.length()) {
            if (s.charAt(i) == '"') {          // " " 里的参数
                i++;
                String ss = "";
                while (s.charAt(i) != '"') {
                    ss += s.charAt(i);
                    i++;
                }
                i++;
                list.add(ss);
            } else if (s.charAt(i) != ' ') {   // 空格 分开的参数
                String ss = "";
                while (i < s.length() && s.charAt(i) != ' ') {
                    ss += s.charAt(i);
                    i++;
                }
                list.add(ss);
            }
            while (i < s.length() && s.charAt(i) == ' ') {  // 过滤空格
                i++;
            }
        }

        System.out.println(list.size());
        list.forEach(e-> {System.out.println(e);});
    }
}

发表于 2025-01-28 18:47:39 回复(0)

看上去很高级的API

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        List<String> cmd = new ArrayList<>();
        while (s.contains("\"")) {
            String u = s.substring(0, s.indexOf("\""));
            cmd.addAll(Arrays.stream(u.split(" ")).collect(Collectors.toList()));
            s = s.substring(s.indexOf("\"")+1);
            cmd.add(s.substring(0, s.indexOf("\"")));
            s = s.substring(s.indexOf("\"")+1);
        }
        cmd.addAll(Arrays.stream(s.split(" ")).collect(Collectors.toList()));
        cmd = cmd.stream().filter(e->!e.equals("")).collect(Collectors.toList());
        System.out.println(cmd.size());
        for (String seq : cmd) {
            System.out.println(seq);
        }
    }
}
发表于 2024-10-02 16:54:30 回复(0)
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String target = in.nextLine();
            //通过书引号“分割字符串
            String [] strs = target.split("\"");

            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < strs.length; i++) {
                //偶数项为不带引号的字符串集
                if(i%2==0){
                    String [] tem;
                    //偶数项除第一项,都以分隔符开头,在结果数组的开头会包含一个空的前导子字符串需要处理掉
                    if(i==0){tem=strs[i].split(" ");}
                    else tem = strs[i].substring(1).split(" ");
                    for (int j = 0; j < tem.length; j++) {
                        list.add(tem[j]);
                    }
                }
                //奇数项为带引号的字符串
                if(i%2==1){
                    list.add(strs[i]);
                }
            }
            System.out.println(list.size());
            for (int i = 0; i <list.size() ; i++) {
                System.out.println(list.get(i));
            }
        }

    }
}

直接分割字符串的方法
发表于 2024-09-15 00:34:31 回复(0)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            String[] str1 = a.split(" ");
            List<String> list = new ArrayList<>();
            for (int i = 0; i < str1.length; i++) {
                if (str1[i].startsWith("\"")) {
                    StringBuilder s = new StringBuilder();
                    if (!str1[i].endsWith("\"")) {
                        s.append(str1[i], 1, str1[i].length());
                        while (!str1[++i].endsWith("\"")) {
                            s.append(" ").append(str1[i]);
                        }
                        s.append(" ").append(str1[i], 0, str1[i].length() - 1);
                    } else {
                        s.append(str1[i], 1, str1[i].length() - 1);
                    }
                    list.add(s.toString());
                } else {
                    list.add(str1[i]);
                }
            }
            System.out.println(list.size());
            list.forEach(System.out::println);
        }
    }
}

发表于 2024-09-10 15:02:41 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        s = " " + s + " ";
        String output = "";
        String tmp = "";
        int q = 0;//引号
        int p = 0;//空格
        int start = 0;
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '"') q++;
            if (q == 0) {
                //不涉及到引号
                if (s.charAt(i) == ' ' || i == 0 || i == s.length() - 1) {
                    p++;
                }
                if (p == 2) {
                    output = output + s.substring(start + 1, i) + '\n';
                    start = i;
                    count++;
                    p = 1;
                }
            } else {
                if (q == 1) {
                    p = 0;//清除空格
                } else if (q == 2) {
                    output = output + s.substring(start + 2, i) + '\n';//清楚引号

                    count++;
                    q = 0;
                    start = i + 1;//下一个空格
                }

            }

        }
        System.out.println(count);
        System.out.println(output);
    }
}

思路就是 
1.假如不存在引号,遇到第一个空格,记录起始位置,遇到第二个空格,就输出起始位置到当前位置的字符串
2.假如存在引号,走另一个分支,遇到第一个引号,记录起始位置,遇到第二个引号,输出起始位置+1到当前位置的字符串,+1为了排除引号

发表于 2024-03-28 11:14:09 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        //分别记录引号和参数的数量
        int count = 0;
        int num = 0;
        StringBuilder b = new StringBuilder();
        for(int i = 0; i < str.length(); i++){
            char c = str.charAt(i);
            b.append(c);
            if(c == ' ' && count % 2 == 0){
                b.append('\n');
                num++;
            }else if(c == '\"'){
                count++;
            }
        }
        System.out.println(num+1);
        System.out.println(b.toString().replace("\"", ""));
    }
}

发表于 2023-11-27 19:28:08 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str=in.nextLine();
        int n=str.length();
        List<String> list=new ArrayList<>();
        for(int i=0,k=0;i<n;i++){
            String s1=str.charAt(i)+"";
            if(s1.equals("\"")){
                for(int j=i+1;j<n;j++){
                    String s2=str.charAt(j)+"";
                      if(s2.equals("\"")){
                            list.add(str.substring(i+1,j));                            
                            i=j;
                            break;
                      }  
                }
                    continue;
            }
            if(s1.equals(" ")){
                list.add(str.substring(k,i));
                k=i+1;
                continue;
            }
            if(i==n-1){
                list.add(str.substring(k,i+1)); 
                break;   
            }
        }
            System.out.println(list.size());
        for(String s:list){
            System.out.println(s);
        }
    }
}


发表于 2023-09-19 13:04:09 回复(0)
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();

        ArrayList<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        // 记录单引号的个数
        int count = 0;
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            if (c == '\"') {
                count++;
            }

            if (c == ' ' && count % 2 == 0) {
                // 去除引号后添加到集合中
                String replace = sb.toString().replace("\"", "");
                list.add(replace);
                sb.delete(0, sb.length());
            } else {
                sb.append(c);
            }
        }

        // 添加最后一个,并去除引号
        list.add(sb.toString().replace("\"", ""));

        // 打印结果
        System.out.println(list.size());
        for (String s : list) {
            System.out.println(s);
        }
    }
}

发表于 2023-08-12 11:50:20 回复(0)
import java.util.*;
//空间复杂度爆炸
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] str=sc.nextLine().split(" ");
        List<String> list=new ArrayList<>();
        int count=0;
        int begin=0;
        int end=0;
        for(int i=0;i<str.length;i++){
            if(!str[i].contains("\"")&&count==0){
                list.add(str[i]);
            }else if(!str[i].contains("\"")&&count==1){
                continue;
            }else if(str[i].startsWith("\"")&&count==0&&(!str[i].endsWith("\""))){
                begin=i;
                count++;
                continue;
            }else if(str[i].endsWith("\"")&&count==1&&(!str[i].startsWith("\""))){
                end=i;
                count=0;
                StringBuffer stbb=new StringBuffer(str[begin]);
                stbb.deleteCharAt(0);
                StringBuffer stbe=new StringBuffer( str[end]);
                stbe.deleteCharAt(str[end].length()-1);
                str[begin]=stbb.toString();
                str[end]=stbe.toString();
                StringBuffer stb=new StringBuffer();
                for(int j=begin;j<end;j++){
                    stb.append(str[j]+" ");
                }
                stb.append(str[end]);
                list.add(stb.toString());
            }else if(str[i].endsWith("\"")&&count==0&&str[i].startsWith("\"")){
                StringBuffer stbn=new StringBuffer(str[i]);
                stbn.deleteCharAt(str[i].length()-1);
                stbn.deleteCharAt(0);
                list.add(stbn.toString());
            }
        }
        System.out.println(list.size());
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
}

发表于 2023-07-19 17:41:56 回复(0)
import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        //n个命令参数有间有n-1空格,所以count从1开始
        int count = 1;
        //记录"的个数
        int flag = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            // 遇到"flag++
            if (ch == '\"') {
                flag++;
                continue;
            }
            //非空字符则拼接
            if (ch != ' ') sb.append(ch);
            //flag % 2 == 0即"d的个数为0或偶数,说明此空字符在命令的末尾
            //或在反"的后面,需要换行
            if (ch == ' ' && flag % 2 == 0) {
                sb.append("\n");
                count++;
            }
            //flag % 2 != 0即"的个数为奇数,说明此空字符在""内,直接拼接字符
            if (ch == ' ' && flag % 2 != 0) sb.append(ch);
        }
        System.out.println(count + "\n" + sb.toString());
    }
}

发表于 2023-07-05 17:34:32 回复(0)
Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            if(str.indexOf("\"")>-1){
                str=str+" ";
                char[] chars = str.toCharArray();
                int yinCount = 0;
                StringBuffer bf = new StringBuffer();
                StringBuffer yinBf = new StringBuffer();
                List<String> list = new ArrayList<String>();
                for(int i=0;i<chars.length;i++){
                    char c = chars[i];
                    if(c=='\"'){
                        yinCount++;
                    }
                    if(yinCount==0){//当前没遇到双引号或者双引号已经完毕
                        if(c!=' '){
                            bf.append(c);
                        }else{//当出现空格
                            if(bf.length()>0) {
                                list.add(bf.toString());//添加
                                bf = new StringBuffer();//重置
                            }
                        }
                    }else{
                        if(c!='\"'){
                             bf.append(c);
                        }
                        if(yinCount==2) { //遇到第二个引号,则添加,bf清空
                            if(bf.length()>0) {                          
                                list.add(bf.toString());//添加
                                bf = new StringBuffer();//重置
                                yinCount=0;
                            }
                        }
                    }
                }  
                System.out.println(list.size());
                for(int i=0;i<list.size();i++){
                    System.out.println(list.get(i));
                }          
            }else{
                String[] strs = str.split(" ");
                System.out.println(strs.length);
                for(int i=0;i<strs.length;i++){
                    System.out.println(strs[i]);
                }
            }
           
        }
发表于 2023-04-16 22:09:01 回复(0)
import java.util.*;
public class Main {
    public static void main(String[]args){
        Scanner scan=new Scanner(System.in);
        String str=scan.nextLine();
        int count=0;//计数
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)=='"'){
                do{
                    i++;
                }while(str.charAt(i)!='"');
            }
            if(str.charAt(i)==' '){
                count++;
            }

        }
        //输出解析的参数个数
        System.out.println(count+1);
        //接下来输出各个参数
        //找一个标志来表示是双引号内部元素
        // boolean flag=false;
        boolean flag=true;
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)=='"'){
                flag=!flag;
            }
            //非空格和引号外的都输出
            if(str.charAt(i)!='"'&&str.charAt(i)!=' '){
                System.out.print(str.charAt(i));
            }
            //引号内的空格
            if(str.charAt(i)==' '&&flag==false){
                System.out.print(str.charAt(i));
            }
            //换行
            if(str.charAt(i)==' '&&flag==true){
                System.out.println();
            }
        }
    }

}

发表于 2023-03-21 18:07:46 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<String> data = new ArrayList<>();
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            //用空格去切分,为了方便切分,最后一位加上一个空格好操作
            String s = in.nextLine().trim()+" ";
            int len = s.length();
            int fenHao = 0;//分号的个数,值域是0,1,2,达到2个后重新清零
            int fromIndex = 0;//开始切割命令的位置
            for (int i = 0; i < len; i++) {
                if (s.charAt(i) == '\"' ) {
                    fenHao++;
                }
                if ((s.charAt(i) == ' ' && fenHao % 2 == 0)) {
                    if (fenHao > 0) {
                        fromIndex = 1 + fromIndex;
                        data.add(s.substring(fromIndex, i - 1));
                        fenHao = 0;
                    } else {
                        data.add(s.substring(fromIndex, i + 1));
                    }
                    fromIndex = i + 1;
                }
            }

        }
        System.out.println(data.size());
        for (String s : data) {
            System.out.println(s);
        }
    }
}


发表于 2023-03-12 18:44:20 回复(0)