Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a string find the first embedded occurrence of an integer

Tags:

java

This was asked in an interview:

Given in any string, get me the first occurence of an integer.

For example

Str98 then it should return 98

Str87uyuy232 -- it should return 87

I gave the answer as loop through the string and compared it with numeric characters, as in

if ((c >= '0') && (c <= '9'))

Then I got the index of the number, parsed it and returned it. Somehow he was not convinced. Can any one share the best possible solution?

like image 950
gmhk Avatar asked Mar 16 '12 18:03

gmhk


People also ask

How do you find the first integer in a string?

To get the first number in a string:Use the search() method to get the index of the first number in the string. The search method takes a regular expression and returns the index of the first match in the string.

How do you find the first occurrence of a number in a string Java?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string.

How do you get an integer from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do you check if a string contains a number?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.


4 Answers

With a regex, it's pretty simple:

String s = new String("Str87uyuy232");
Matcher matcher = Pattern.compile("\\d+").matcher(s);
matcher.find();
int i = Integer.valueOf(matcher.group());

(Thanks to Eric Mariacher)

like image 52
cdeszaq Avatar answered Oct 18 '22 03:10

cdeszaq


Using java.util.Scanner :

int res = new Scanner("Str87uyuy232").useDelimiter("\\D+").nextInt();

The purpose of a Scanner is to extract tokens from an input (here, a String). Tokens are sequences of characters separated by delimiters. By default, the delimiter of a Scanner is the whitespace, and the tokens are thus whitespace-delimited words.

Here, I use the delimiter \D+, which means "anything that is not a digit". The tokens that our Scanner can read in our string are "87" and "232". The nextInt() method will read the first one.

nextInt() throws java.util.NoSuchElementException if there is no token to read. Call the method hasNextInt() before calling nextInt(), to check that there is something to read.

like image 31
barjak Avatar answered Oct 18 '22 03:10

barjak


There are two issues with this solution.

  1. Consider the test cases - there are 2 characters '8' and '7', and they both form the integer 87 that you should be returning. (This is the main issue)

  2. This is somewhat pedantic, but the integer value of the character '0' isn't necessarily less than the value of '1', '2', etc. It probably almost always is, but I imagine interviewers like to see this sort of care. A better solution would be

    if (Character.isDigit(c)) { ... }

There are plenty of different ways to do this. My first thought would be:

int i = 0;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
int j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
return Integer.parseInt(string.substring(i, j)); // might be an off-by-1 here

Of course, as mentioned in the comments, using the regex functionality in Java is likely the best way to do this. But of course many interviewers ask you to do things like this without libraries, etc...

like image 18
mfsiega Avatar answered Oct 18 '22 03:10

mfsiega


String input = "Str87uyuy232";
Matcher m = Pattern.compile("[^0-9]*([0-9]+).*").matcher(input);
if (m.matches()) {
    System.out.println(m.group(1));
}
like image 7
Matt Avatar answered Oct 18 '22 01:10

Matt