Reputation: 141
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 ??
Upvotes: 4
Views: 19416
Reputation: 1384
String thisString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
Upvotes: 1
Reputation: 7461
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 String
s 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...
Upvotes: 5
Reputation: 740
Yes you can.
Use String.split()
and Integer.parseInt()
as show below:
String[] split = line.split("\\s+");
List<Integer> numbers = new ArrayList<Integer>();
for (String num: split) {
try {
numbers.add(Integer.parseInt(num));
} catch (NumberFormatException ex) {
// not a number
}
}
Upvotes: 0
Reputation: 469
You could start off by splitting the data into a array:
String [] lineSplit = line.split("\\s+");
And then begine parsing the data into individual variables:
int foo = 0;
for(int i = 0; i < lineSplit.length; i++) {
if(lineSplit[i].matches("\\d+") {
foo = Integer.parseInt(lineSplit[i]);
}else {
//Do something else...
}
}
And repeat the above for different data types and add variable etc. to get the desired result.
Upvotes: 0
Reputation: 3449
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
Upvotes: 3