Suppose I have String s = "123 USA"
, how can I obtain only the number i.e '123' that is in the String? By that I mean what is the most efficient way of doing it?
Asked
Active
Viewed 51 times
-4

Nik_stack
- 213
- 2
- 7
- 17
-
2What should the string "3844 GRE 2345 USA 239 ESP 3494" result in? Or should every input string have the format `[0-9]+ [A-Z]+`? – Tobias Jun 29 '14 at 21:51
-
Is every input delimited by a space? – MadProgrammer Jun 29 '14 at 21:58
3 Answers
0
- Split the
String
on the space character. - For each String in the resulting
String[]
, use the method from this answer to determine whether it is a valid integer or not. If it is a valid integer, then output that integer. Otherwise, ignore it.

Community
- 1
- 1

merlin2011
- 71,677
- 44
- 195
- 329
0
If you know where the numbers are in the the string, i would do something like this.
String[] split = s.split();
This will give you an array equivalent to
String[] split = ["123", "USA"];
The split function will default to splitting by spaces(I believe).
From there you can use
int num = Integer.parseInt(split[0]);
// num = 123;
to convert the fist index of the split array into an int.

bbusching
- 79
- 1
0
s.replaceAll("\\D+", " ").trim()
\\D+
matches non-digitstrim()
clears whitespace
Example:
String testString = " ##!@! (!#)!@ 123 USA 312";
Output: 123 312
If there is more than one number, the next step may be to use String.split()
.
To convert a String to an integer: Integer.parseInt(string)

bbalchev
- 827
- 1
- 9
- 19