使用状态机的思想
import java.util.Scanner;
import java.util.*;
public class Main {
public static int STATE_CHAR = 2;
public static int STATE_STR = 1;
public static int STATE_BEGIN = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.nextLine();
List<String> result = function(str);
System.out.println(result.size());
for (String ss : result) {
System.out.println(ss);
}
}
}
public static List<String> function(String str) {
ArrayList<String> list = new ArrayList<>();
int state = STATE_BEGIN;
int start = 0;
for (int i = 0; i < str.length(); i++) {
switch(state) {
case 0 :
if (str.charAt(i) == '\"'){
state = STATE_CHAR;
start = i;
} else if (str.charAt(i) == ' ') {
state = STATE_BEGIN;
} else {
state = STATE_STR;
start = i;
if (i == str.length() - 1) {
list.add(new String(str.substring(start, i + 1)));
}
}
break;
case 1 :
if (str.charAt(i) == ' ' || i == str.length() - 1) {
list.add(new String(str.substring(start, i + 1)));
start = i;
state = STATE_BEGIN;
}
break;
case 2 :
if(str.charAt(i) == '\"') {
list.add(new String(str.substring(start + 1, i)));
start = i + 1;
state = STATE_BEGIN;
}
break;
}
}
return list;
}
}

京公网安备 11010502036488号