Reputation: 1533
Very simple question - I have a string that looks like PR:MTH 1 MTR 7
. I want to extract the numbers in that string to integer variables.
The problem is that I don't know how many digits these integers have. for example PR:MTH 100000 MTR 777
is also a valid string. So I can't specify the exact indexes where the numbers are.
All we can say for sure is that the MSB of the first number is at index 7 (I counted).
Is there some String method or StringBuilder method in java that does this? or do I need to write one of my own?
Upvotes: 0
Views: 102
Reputation: 425198
To solve the general case, use regex to find the numbers:
String number1 = str.replaceAll("\\D*(\\d+).*", "$1");
String number2 = str.replaceAll("\\D*\\d+\\D+(\\d+).*", "$1");
This has the advantage of working with input that doesn't have a clear delimiter, eg if the input string was
foo123bar456baz
the above code would successfully extract 123
and 456
.
Upvotes: 0
Reputation: 21995
String#split
is your friend in this situation
Split the string with spaces and colons and parse the corresponding indexes.
String s = "PR:MTH 100000 MTR 777";
String[] split = s.split("[ :]");
int one = Integer.parseInt(split[2]);
int two = Integer.parseInt(split[4]);
Upvotes: 3
Reputation: 267
You can do yourString.split(" ");
and iterate that array searching for all the numbers, using a try-catch block. In order to save them, you can use an ArrayList<Integer>
.
I would do something like:
String myString = "dsfsd 12 12 dd";
ArrayList<Integer> numbers = new ArrayList<>();
String[] splitString = myString.split(" ");
for (String split : splitString) {
try {
numbers.add(Integer.valueOf(split));
} catch (java.lang.NumberFormatException e) {
//not a number
}
}
System.out.printf("I have %d numbers in my String! \n", numbers.size());
In order to obtain the numbers, you just need to iterate the ArrayList
.
for (Integer number : numbers) {
//your code
System.out.println(number);
}
Hope this helps you!
Upvotes: 1
Reputation: 86
you should try split(" ") and then take values u need and convert to integer
Upvotes: 1