【问题标题】:split a string with the space bar用空格键拆分字符串
【发布时间】:2023-03-28 07:03:01
【问题描述】:

以下是我的java代码

我要输入:asd 123456 hellohello

输出:

asd

123456

你好

但是出现错误。谁能帮帮我?

封装测试;

import java.util.Scanner;
public class test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner (System.in);
        String cs = sc.next();

        String[] output = cs.split("\\s+");
        System.out.println(output[0]);
        System.out.println(output[1]);
        System.out.println(output[2]);
    }
}

【问题讨论】:

  • sc.nextLine();替换sc.next();
  • 我学到了新东西谢谢

标签: java split spaces


【解决方案1】:

我已经用您的代码修复了一些问题:

import java.util.Scanner;
public class SplitStringWithSpace {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String cs = sc.nextLine();
        //close the open resource for memory efficiency
        sc.close();
        System.out.println(cs);

        String[] output = cs.split("\\s+");
        for (String retval : output) {
            System.out.println(retval);
        }
    }
}
  • 使用增强的 for 循环,因此您不必手动导航数组。
  • 使用完资源后关闭它。

【讨论】:

  • 谢谢你我唯一的问题:)
  • @TLam 不客气!如果答案对您有帮助,请点赞/选为正确答案:)
【解决方案2】:

next() 只返回输入中的下一个标记而不是整行,您的代码将抛出 ArrayIndexOutOfBoundsException,因为它代表 bcoz output 的长度等于 1。

你需要nextLine() 方法来获取整行。

【讨论】:

  • 谢谢你的问题>~
【解决方案3】:

这里sc.next() 使用spaces 分隔符。所以给定输入为foo bar,你会得到:

sc.next(); //`foo`
sc.next(); //`bar`

您可以选择sc.nextLint() 并按原样使用其余代码。如果你必须继续使用sc.next(),你可以试试这个代码sn-p。

while(sc.hasNext()) { //run until user press enter key
  System.out.println(sc.next());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 2015-09-14
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多