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/

相关文章:

string - 从 NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys 获取 [String]

java - 替换字符串中的特殊字符

java - 数据透视表刷新并将代码保存在 aspose 单元格中,用于 java 损坏 excel 文件

java - 尝试将小程序添加到我的网站时出现 NoClassDefFound 错误

java - 使用 @Query 使用 Spring Data 创建自定义查询

string - 使用 Matlab Coder 的 C++ 兼容函数将整数转换为字符串

java - 为什么 Google Guava Multimap.get(Key) 方法不接受对象?

BASH - 根据条件将文件拆分为多个文件

ruby-on-rails - Rails 由最后一个分隔符分割

java - 在多个字符上拆分字符串