Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To get the value after space in String Java

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 ??

like image 613
androidcodes Avatar asked Oct 21 '25 04:10

androidcodes


2 Answers

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...
like image 81
Dmitry Ginzburg Avatar answered Oct 23 '25 17:10

Dmitry Ginzburg


    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
like image 35
mtyurt Avatar answered Oct 23 '25 18:10

mtyurt