【问题标题】:How to divide string by empty space in Java如何在Java中将字符串除以空格
【发布时间】:2016-04-04 18:42:46
【问题描述】:

所以,我有以下情况:

private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String line= reader.readLine();
String first = ?
String second = ?

所以,我知道用户会输入这样的内容:love cat and dogs。 我希望第一个词(在这种情况下是爱)总是首先在 String 中,而其他一切都在 String 中。我怎样才能做到尽可能简单?

【问题讨论】:

标签: java bufferedreader readline


【解决方案1】:
String line = "love cats and dogs";
// split into 2 parts
String[] parts = line.split(" ",2);

String first = parts[0];
String second = parts[1];

【讨论】:

    【解决方案2】:

    简单地说:

    int splitIndex = line.indexOf(" ");
    String first = line.substring(0, splitIndex);
    String second = line.substring(splitIndex + 1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 2011-07-24
      • 2016-02-21
      • 2011-09-30
      • 2021-09-04
      相关资源
      最近更新 更多