awfulwaffle
awfulwaffle

Reputation: 95

How to parse multi-digit integers from string

I'm working on assignment here, part of which requires me to parse integers from a string that has groups of digits separated by any other character. I know I can use the wrapper class method Integer.parseInt(string) to parse ints from a string containing just digits, but how would I go about doing it in this case? So far, I've considered doing a linear search of the string and assigning a variable to the first index where a digit appears and the index after the last digit appears and creating a temporary substring based on these indices from which to parse the int. Is this a valid approach? Perhaps there is a more efficient one?

Upvotes: 2

Views: 7231

Answers (4)

Allen Z.
Allen Z.

Reputation: 1588

Try this:

Integer findNumber(String s){
 List<String> num = Arrays.asList(s.split("[^0-9]"));
 for(String n : num) if(!n.isEmpty()) return Integer.parseInt(n);
}

The first line splits s around portions that match non-digit characters.

The second line then finds the first non-empty string of digits in the List.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425013

Let the API do the work, leading to this simple one-liner:

int i = Integer.parseInt(input.replaceAll("\\D", ""));

Explanation:

Upvotes: 2

Sachin
Sachin

Reputation: 18747

If it can be any character (one or more), then this might be helpful:

String[] aarray = str.split("[^\\d]+");

E.g.:

String str = "12fdvvsd34.;h56s67.45c56";
String[] aarray = str.split("[^\\d]+");

for(int i = 0; i < aarray.length; i++)
    System.out.println(Integer.parseInt(aarray[i]));

Output:

12
34
56
67
45
56

Upvotes: 5

duffymo
duffymo

Reputation: 308763

You can you java.util.String split method If you have a String with substrings separated by a token:

String data "123.345.55.66";
String [] fields = data.split(".");

If that's not what you want, you can slog through the details by looping over the String character by character:

for (int i = 0; i < data.size(); ++i) {
    char c = data.charAt(i);
    // manipulate as needed.
}

Upvotes: 0

Related Questions