首页 > 试题广场 >

参数解析

[编程题]参数解析
  • 热度指数:158004 时间限制: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();
        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)
自己写。递归。

import java.util.*;

public class Main {
    public static List<String> res = new ArrayList<>(); //保存分解后的参数
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.nextLine();
            count(str);
            System.out.println(res.size());
            for (String s : res) {
                System.out.println(s);
            }
        }
    }
    public static void count(String str) {
        if (str == null) { 
            return;
        }
        int i = str.indexOf("\"");
        if (i > 0) { //如果有引号
            String sub1 = str.substring(0, i);
            count(sub1);//将引号之前的部分分解出来单独分析
            String sub2 = str.substring(i + 1);//删除前引号以及前面的部分,也就是说保留前引号后面的部分
            int j = sub2.indexOf("\"");//找到对应的后引号的坐标
            String sub3 = sub2.substring(0, j);//截取前后引号中间的内容
            res.add(sub3);//将前后引号中间的内容添加到结果中
            if (j + 2 < sub2.length()) { //判断后引号后面是否还有内容,如果有就进行下一轮判断
                count(sub2.substring(j + 2));
            }
        } else {  //如果没有引号,则按空格分解,依次添加到结果中
            String[] strs = str.split(" ");
            for (String s : strs) {
                res.add(s);
            }
        }
    }
}

发表于 2023-02-24 17:15:40 回复(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 str = in.nextLine();
        // 定义一个集合,用于存储解析的参数
        List<String> strLists = new ArrayList<>();
        // 对字符串进行参数解析
        stringAnalysis(str, strLists);
        // 输出结果
        System.out.println(strLists.size());
        strLists.forEach(p-> {
            System.out.println(p);
        });
    }
    /**
     * 对输入的字符串进行解析.
     */
    private static void stringAnalysis(String str, List<String> strLists) {
        // 定义一个字符串,用来表示解析的字符串
        String analysisStr = "";
        // 定义一个变量,用于存储遇到冒号的次数
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != ' ' && str.charAt(i) != '"') {
                // 如果遇到的不为空格,也不是冒号,则添加
                analysisStr = analysisStr + str.charAt(i);
            } else if (str.charAt(i) == ' ' && count == 0) {
                // 遇到空格,但不是冒号内的,则将analysisStr添加到列表,并重置
                if (!analysisStr.equals("")) {
                    strLists.add(analysisStr);
                    analysisStr = "";
                }
            } else if (str.charAt(i) == ' ' && count != 0) {
                // 如果遇到冒号中的空格,还是要添加
                analysisStr = analysisStr + str.charAt(i);
            } else if (str.charAt(i) == '"') {
                if (count == 0 ) {
                    // 如果第一次遇到冒号,先将字符串重置
                    analysisStr = "";
                }
                count = count + 1;
                if (count == 2) {
                    // 第二次遇到,冒号,先将前一次解析添加,然后重置
                    strLists.add(analysisStr);
                    count = 0;
                    analysisStr = "";
                }
            }
        }
        if (!analysisStr.equals("")) {
            // 循环完,将最后一个添加到列表
            strLists.add(analysisStr);
        }
    }
}

发表于 2023-02-15 16:15:54 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String s = sc.nextLine();
        StringBuilder sb = new StringBuilder();
        ArrayList<String> list = new ArrayList();
        boolean flag = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            //注意这里是可以这么写的 c == '”'
            if (c == '"') {
                //遇到第一个引号 flag为true,第二个引号 flag为false
                flag = flag ? false : true;
                continue;//继续遍历下一个字符
            }
            //如果c是空格 ,且flag为false时,即没有引号 或已经是第二个引号结束
            if (c == ' ' && !flag) {
                list.add(sb.toString());//往集合中添加当前拼接到的字符串
                //我在这里学到了sb如何置空,只需要重新定义即可
                sb = new StringBuilder();//置空  重新遍历下一个字符
            } else {
                //即不是空格,也不是引号,就继续往里添加
                sb.append(c);
            }
        }
        //注意这里还需要加一次,即把第四个元素加上,因为前面的循环只能加上前三个
        list.add(sb.toString());
        System.out.println(list.size());
        //遍历输出即可
        for (String s1 : list) {
            System.out.println(s1);
        }

    }
}

发表于 2022-10-26 11:31:32 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            int count = 0;
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < str.length(); i++) {
                if (Character.isWhitespace(str.charAt(i))) {
                    continue;
                } else if (str.charAt(i) == '"') {
                    int j = i + 1;
                    while (j < str.length() && str.charAt(j) != '"') {
                        j++;
                    }
                    list.add(str.substring(i + 1, j));
                    i = j;
                    count++;
                } else {
                    int j = i;
                    while (j < str.length() && !Character.isWhitespace(str.charAt(j))) j++;
                    list.add(str.substring(i, j));
                    i = j;
                    count++;
                }
            }

            System.out.println(count);
            for (String s : list) {
                System.out.println(s);
            }
        }
    }
}

发表于 2022-10-21 21:54:44 回复(0)
感觉好多人写得很长,好像没那么繁琐吧。。。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by ljw at 16:54 on 2022/10/03.
 */
public class HJ74_star {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();

        boolean allow = true;//允许截断
        int count = 0;
        StringBuilder sb = new StringBuilder();
        for (char ch : line.toCharArray()) {
            if (ch == '"') {
                allow = !allow;//允许截断标志改变,且不保存
            } else {
                sb.append(ch);//允许截断标志不变,但要保存
            }
            if (allow && ch == ' ') {
                sb.append("\n");
                count++;
            }
        }
        System.out.println(count + 1);
        System.out.println(sb);
    }
}


发表于 2022-10-03 17:24:58 回复(2)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        char[] chs = str.toCharArray();
        int count = 0;
        for(int i = 0; i < chs.length; i++) {
            if(chs[i] == '"') {
                do {
                    i++;
                }while(chs[i] != '"');
            }

            if(chs[i] == ' ') {
                count++;
            }
        }
        System.out.println(count + 1);

        int flag = 1;
        for(int i = 0; i < chs.length; i++) {
            if(chs[i] == '"') {
                flag ^= 1;
            }
            if(chs[i] != ' ' && chs[i] != '"') {
                System.out.print(chs[i]);
            }
            if(chs[i] == ' ' && flag == 0) {
                System.out.print(chs[i]);
            }
            if(chs[i] == ' ' && flag == 1) {
                System.out.println();
            }
        }
    }
}
发表于 2022-09-28 20:59:08 回复(0)
测试用例应该都是这样的:只有第一个是命令字,肯定不包含空格或引号,单独处理,剩下的都是普通字符串,分有引号无引号处理就行。
运行时间:12ms
超过96.20% 用Java提交的代码
占用内存:9480KB
超过93.49% 用Java提交的代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        Solution sl = new Solution();
        System.out.println(sl.detach(input));
    }
}

class Solution {
    public StringBuilder detach(String input) {
        int len = input.length(), pos = 0, count = 0;
        StringBuilder sb = new StringBuilder();
        while (pos < len) {
            char cur = input.charAt(pos++);
            if (cur == ' ') {
                sb.append("\n");
                count++;
                break;
            }
            sb.append(cur);
        }

        while (pos < len) {
            if (input.charAt(pos) == '\"') {
                pos++;
                while (pos < len) {
                    char cur = input.charAt(pos++);
                    if (cur == '\"') {
                        sb.append("\n");
                        pos++;
                        break;
                    } else {
                        sb.append(cur);
                    }
                }
            } else {
                while (pos < len) {
                    char cur = input.charAt(pos++);
                    if (cur == ' ') {
                        sb.append("\n");
                        break;
                    } else if (pos == len) {
                        sb.append(cur);
                        sb.append("\n");
                        break;
                    } else {
                        sb.append(cur);
                    }
                }
            }
            count++;
        }
        return new StringBuilder().append(count).append("\n").append(sb);
    }
}



发表于 2022-09-05 21:21:52 回复(0)

问题信息

难度:
82条回答 36247浏览

热门推荐

通过挑战的用户

查看代码