java - 分割字符串 Java 空间

标签 java string split whitespace

如果有人能帮助我,那就太好了。

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

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

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

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

有人可以帮忙吗?谢谢!

最佳答案

在确定数组中的第二个元素存在之前,不要尝试访问它。示例:

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 的元素之前,此代码始终会检查 comando2.length。你也应该这样做。

关于java - 分割字符串 Java 空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955146/

相关文章:

iphone - 在 NSString 的特定行分割字符串

java - 无法在 Eclipse Kepler 中安装颠覆性连接器

java - 强制子类在加载时执行某些操作

java - 使用 java String.split 从文件动态读取

c# - 如何在没有任何条件语句或运算符的情况下编写条件语句?

javascript - 在 JavaScript 中匹配和拆分中文逗号的正则表达式

mysql - 将元数据记录为实体表的一部分还是单独的?

java - Java(Spring 应用程序)和 C# 之间的数据交换

java - 如何获取属于一项调查的所有问题?

javascript - 使用 AngularJS 中的多个输入字段编辑分隔字符串