拆分字符串Java空间

时间:2015-01-15 00:50:30

标签: java string split whitespace

如果有人可以帮助我,那就太棒了。

我正在尝试使用Java的Split命令,使用空格分割String但问题是,字符串可能没有空格,这意味着它只是一个简单的顺序(而不是“输入2”将是“退出”)

Scanner SC = new Scanner(System.in);
String comando = SC.nextLine();
String[] comando2 = comando.split("\\s+");
String first = comando2[0];
String second = comando2[1];

当我尝试这个时,如果我写“输入3”因为“first = enter”和“second = 3”,它会起作用,但是如果我写“exit”它会抛出一个错误,因为第二个没有值。 我想分割字符串,所以当我尝试以下内容时:

if ( comando.equalsIgnoreCase("exit"))
    // something here
else if ( first.equalsIgnoreCase("enter"))
    // and use String "second"

有人可以帮忙吗?谢谢!

3 个答案:

答案 0 :(得分:4)

请勿尝试访问数组中的第二个元素,直到您确定它存在为止。例如:

if(comando2.length < 1) {
    // the user typed only spaces
} else {
    String first = comando2[0];
    if(first.equalsIgnoreCase("exit")) { // or comando.equalsIgnoreCase("exit"), depending on whether the user is allowed to type things after "exit"
        // something here

    } else if(first.equalsIgnoreCase("enter")) {
        if(comando2.length < 2) {
            // they typed "enter" by itself; what do you want to do?
            // (probably print an error message)
        } else {
            String second = comando2[1];
            // do something here
        }
    }
}

请注意,在尝试访问comando2.length的元素之前,此代码始终会检查comando2。你也应该这样做。

答案 1 :(得分:1)

这个怎么样?

...
String[] comando2 = comando.split("\\s+");
String first = comando2.length > 0 ? comando2[0] : null;
String second = comando2.length > 1 ? comando2[1] : null;
...

您的问题是您在知道数组元素是否存在之前访问它。这样,如果数组足够长,则获取值,否则获取null。

如果a ? b : c为真,则表达式b评估为a,如果c为假,则a评估为? :。这个{{1}}运算符称为三元运算符。

答案 2 :(得分:-1)

为什么不检查它是否有空格,如果有空格则处理不同:

if (comando.contains(" "))
{
    String[] comando2 = comando.split(" ");
    String first = comando2[0];
    String second = comando2[1];
}
else
{
    String first = comando;
}
相关问题