题解 | #参数解析#

参数解析

https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String command = in.nextLine();
        // 用队列来存储分割后的参数 先进先出 便于输出
        LinkedList<String> queue = new LinkedList<String>();
        for (; ; ) {
            int index = command.indexOf("\"");
            if (index == 0) {
                // 如果第一个字符就是双引号 
                // 则将第一个和第二个双引号之间的字符串入队
                int quota2 = command.indexOf("\"", 1);
                queue.offer(command.substring(1, quota2));
                if (quota2 == command.length() - 1) {
                    break;
                } else {
                    command = command.substring(quota2 + 1);
                }
            } else if (index == -1) {
                offer(queue, command.split(" "));
                break;
            } else {
                offer(queue, command.substring(0, index).split(" "));
                command = command.substring(index);
            }
        }
        System.out.println(queue.size());
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }

    static void offer(LinkedList<String> queue, String[] strs) {
        for (String str : strs) {
            if (!str.isEmpty()) {
                queue.offer(str);
            }
        }
    }
}

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String command = in.nextLine();
        // true 表示引号内容开始 false表示引号内容结束
        boolean flag = false;
        StringBuilder sb = new StringBuilder();
        LinkedList<String> queue = new LinkedList<String>();
        for (int i = 0; i < command.length(); i++) {
            // 有两种情况sb是一个参数
            // 1: 遇到空格(参数分割符, 引号内的不算)
            // 2: 走到结尾
            if ((command.charAt(i) == ' ' && !flag)
                    || i == command.length() - 1) {
                queue.offer(sb.toString());
                sb = new StringBuilder();
            } else if (command.charAt(i) == '"') {
                flag = !flag;
            } else {
                sb.append(command.charAt(i));
            }
        }
        System.out.println(queue.size());
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}


#华为笔试#
全部评论

相关推荐

云边有个小卖铺儿:校招生违约率低,所以我要高😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务