如何将字符串从第一个空格中拆分出来,仅 Java 出现

2022-09-01 19:39:09

我试图使用字符串拆分字符串。Index 和 string.length,但我收到一个错误,字符串超出范围。我该如何解决这个问题?

while (in.hasNextLine())  {

    String temp = in.nextLine().replaceAll("[<>]", "");
    temp.trim();

    String nickname = temp.substring(temp.indexOf(' '));
    String content = temp.substring(' ' + temp.length()-1);

    System.out.println(content);

答案 1

使用带有限制的 java.lang.String 拆分函数。

String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));

您将获得:

cr: some, cdr: string with spaces

答案 2

一定是围绕这个:

String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);