我正在尝试将输入扫描仪的两行字符串分成一个大字符串,然后分成两个单独的字符串(如下面的示例和预期输出所示)。
伪代码
Scanner s = new Scanner("Fred: 18Bob D: 20").useDelimiter(":") //delimiter is probably pointless here
List<String> list = new ArrayList<>();
while (s.hasNext()) {
String str = "";
if (//check if next token is str) {
str = str + s.next();
}
if (//check if next token is :) {
//before the : will always be a name of arbitary token length (such as Fred,
//and Bob D), I also need to split "name: int" to "name : int" to achieve this
str = str + ": " + s.next();
}
if (//check if next token is alphanumeral) {
//split the alphanumeral then add the int to str then the character
str = str + s.next() + "\n" + s.next() //of course this won't work
//since s.next(will go onto the letter 'D')
}
else {
//more code if needed otherwise make the above if statement an else
}
list.add(str);
}
System.out.println(list);
预期输出
Fred: 18
Bob D: 20
我无法弄清楚我是如何做到这一点的。如果有任何关于实现这一目标的指示,我将非常感激。
另外,一个简单的问题。 \n
和line.separator
之间有什么区别?我应该何时使用每个?从我在课堂代码中看到的简单示例中,line.separator
已用于分隔List<String>
中的项目,这是我唯一的经验。
答案 0 :(得分:0)
您可以尝试以下代码段:
List<String> list = new ArrayList<String>();
String str="";
while(s.hasNext()){
if(s.hasNextInt()){
str+=s.nextInt()+" ";
}
else {
String tmpData = s.next();
String pattern = ".*?(\\d+).*";
if(tmpData.matches(pattern)){
String firstNumber = tmpData.replaceFirst(".*?(\\d+).*", "$1");
str+=firstNumber;
list.add(str);
str="";
str+=tmpData.replace(firstNumber, "")+" ";
}else{
str+=tmpData;
}
}
}
list.add(str);
System.out.println(list);