如何在Java中拆分输入字符串?

时间:2016-01-31 14:09:32

标签: java string split trim

用户在java中输入一个字符串,我必须将其拆分为不同的组件。

Scanner scanner = new Scanner(System.in);
String test = scanner.next();

// split the test variable using the split method
String [] parts = test.split(" ,", 3);

s[i].setFirstName(parts[0].trim());
s[i].setlastName(parts[1].trim());
s[i].setID(Integer.parseInt(parts[2].trim()));
s[i].setgrade(Integer.parseInt(parts[3].trim()));

但它不起作用。我只能得到第一个出现的词。

3 个答案:

答案 0 :(得分:0)

使用nextLine()而不是next()来解决问题。

如需进一步参考,请查看the docs

答案 1 :(得分:0)

发表评论

  

我只能得到一个词出现。它没有阅读任何程序   词语的

使用nextLine()代替next()

next()只会返回空格前的内容。

返回当前行后,

nextLine()会自动将扫描仪向下移动。

name = scanner.nextLine();

Scanner doc

答案 2 :(得分:0)

更改

String test = scanner.next();

String test = scanner.nextLine();

scanner.next()在遇到空格时会说一句话。 nextLine()将考虑整条线。