我是java编程的初学者。我想从“XX X X,XX”这样的文本中获取第一个单词。但我得到的答案是“XX XX”。如何改进我的代码? 这是我的代码:
ArrayList<String> optionCode = new ArrayList<String>();
while (File.hasNext()) {
String code = File.nextLine();
String code1= null;
if(code.contains(" ")) {
code1 = code.substring(0, code.indexOf(" "));
}
else {
code1 = code;
}
optionCode.add(code1);
}
输入txt:
LD F0, 0(R1)
输出:
LD
F0
0(R1)
这是我想要的输出:
LD
最佳答案
上面的代码看起来不错,并且应该可以工作,假设这里的空白只是一个空格。
或者你可以尝试
String [] arr = code.split("\\s+"); // split on any whitespace
// of course test that arr has length before doing this
optionCode.add(arr[0]);
关于java - 子串(IndexOf( )),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676713/