我想知道是否可以将出现的字符分配给变量,直到我遇到一个空格字符。例如,如果我有一个字符串"17 23 4 54 6 343 4"
,我如何将第一个数字17赋值给一个变量,然后将随后的数字赋值给变量。
发布于 2010-12-01 05:29:07
String values = "17 23 4 54 6 343 4";
String[] variables = values.split("\\s");
现在您已经有了一个数组variables
,它在variables[0]
中包含17,在variables[1]
中包含23,依此类推。
发布于 2010-12-01 05:29:48
我会使用Scanner
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String input = "17 23 4 54 6 343 4";
Scanner s = new Scanner(input);
while (s.hasNextInt())
System.out.println(s.nextInt());
}
}
输出:
17
23
4
54
6
343
4
如何将第一个数字17赋给变量,以及随后的数字。
如果你想把第一个值放在一个变量里,把剩下的字符串放在另一个变量里,你可以这样做:
String input = "17 23 4 54 6 343 4";
Scanner s = new Scanner(input);
int firstValue = s.nextInt();
String remaining = s.nextLine();
发布于 2010-12-01 05:28:18
只需使用split和list或Scanner即可
https://stackoverflow.com/questions/4318836
复制相似问题