-4

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?

Nik_stack
  • 213
  • 2
  • 7
  • 17

3 Answers3

0
  1. Split the String on the space character.
  2. 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-digits
  • trim() 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