自己写的。递归。
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
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);
}
}
}
}
查看1道真题和解析
