substring(IndexOf())

时间:2014-03-27 01:43:36

标签: java substring

我是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

3 个答案:

答案 0 :(得分:1)

上面的代码看起来不错,应该假设这里的空白只是一个空格。

或者你可以尝试

String [] arr = code.split("\\s+");   // split on any whitespace
// of course test that arr has length before doing this
optionCode.add(arr[0]);

答案 1 :(得分:0)

所有这些

String code1= null;

if(code.contains(" ")) {
    code1 = code.substring(0, code.indexOf(" "));
}
else {
    code1 = code;
}

可以缩减为

int spaceIdx = code.indexOf(" ");
String code1 = ((spaceIdx == -1) ? code.substring(0, spaceIdx) : code);

答案 2 :(得分:0)

我理解你的意思。只需使用以下代码:

ArrayList<String> optionCode = new ArrayList<String>();
while (File.hasNext()) {
    String code = File.nextLine();
    String[] arr = code.split("[^a-zA-Z]");
    for (int i = 0; i < arr.length; i ++){
        optionCode.add(arr[i]);
    }
}