I have String of values .
Like as
String line= "cpu 74608 2520 24433 1117073 6176 4054";
i just want to extract these Values and store them in different variables.
Is there any way that i can get the Numeric values after every space ??
One of the options you have is to use String.split method. It accepts regex, so you can skip any number of spaces:
String[] values = line.split("\\s*");
Then you'll have to convert these Strings to the values you need:
int firstNum = Integer.valueOf(values[1]);
// anything like this
If you're OK with storing it as an array/list, but not as different variables, maybe you'll want to extract all numbers this way (Java 8):
int[] numbers = Stream.of(values)
.filter(str -> str.matches("-?\\d+"))
.mapToInt(Integer::valueOf)
.toArray();
Maybe, the easier way would be using Scanner:
Scanner scanner = new Scanner(line);
String firstStr = scanner.next();
int firstNum = scanner.nextInt();
// and so on...
String input = "123 456 123 578";
String[] numbers = input.split(" ");
for (String s : numbers) {
System.out.println(Integer.valueOf(s));
}
output:
123
456
123
578
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With