CC-19 : Extract decimal number from String (Atoi).
Description:
Given input String str, extract a decimal number from and return the same.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| str="abc123"; | 123.0 |
| str="-123abc"; | -123.0 |
| str="asz-123.45673def" | -123.45673 |
| str1="-0.456734def" | -0.456734 |
Pseudocode:
| The java method should accept following input parameters: str (String). |
| Initialize char array chars=str.toCharArray(). |
| Initialize String extracted=””. We will use this variable to store the extracted integer. |
| Initialize integer variable idx=0; |
| Iterate through chars using while loop till chars[idx] is non-digit and non-sign character:
Increment idx by 1.
|
| Initialize boolean variable signFound=false. |
| If chars[idx] is a +/- sign:
add chars[idx] to extracted.
Increment idx by 1.
Set signFound to true.
|
| If signFound is true and next character is not a number, this String is not a valid number, return from program. |
| Initialize boolean variable preDecimaFound=false. |
| Iterate through chars using while loop till chars[idx] is a digit character:
add chars[idx] to extracted.
Increment idx by 1
Set preDecimalFound to true.
|
| Initialize boolean variable decimalFound=false. |
| If chars[idx] is a “.” decimal:
add chars[idx] to extracted.
Increment idx by 1.
Set decimalFound to true.
|
| If decimalFound is true and next character is not a number, this String is not a valid number, return from program. |
| • Initialize boolean variable postDecimalFound=false. |
| Iterate through chars using while loop till chars[idx] is a digit character:
o add chars[idx] to extracted.
Increment idx by 1.
o Set postDecimalFound to true.
|
| Use Float.parseFloat() to extract float from extracted. Return the parsed float number from the program. |
The above algorithm can also be completed using Java String and regex APIs:
| Regex patterns and matchers can be used to match the float number in the input str. |
| Following regexes are used to solve this problem:
[-+]?': This matches (`+` or `-`) at the start of the number.
'\d*\.\d+': matches zero or more digits before the decimal point.
'\.': matches the decimal point.
'\d+': matches digits after the decimal point.
'|': This acts as an OR operator to include other possible matches.
'[-+]?': This allows for an optional sign (`+` or `-`) at the start of the number.
'\d+': This matches whole numbers, which do not have decimal points.
|
| Set Pattern p= Pattern.compile("[-+]?\d+\.\d+|[-+]?\d+"); |
| Use Pattern.matcher() method to create a matcher for above regex. |
| Use Matcher.group() to extract a String matching above regex to String extracted. |
| Use Float.parseFloat() to extract float from extracted. Return the parsed float number from the program. |
Code:
public float stringExtractNumberAtoi(String str) {
char[] chars=str.toCharArray();
int idx=0;
String extracted="";
while (idx < chars.length && chars[idx] !='+'
&& chars[idx] != '-' && ! Character.isDigit(chars[idx])) {
idx++;
}
boolean signFound=false;
if (idx < chars.length && (chars[idx]=='+' || chars[idx]=='-')) {
extracted+=chars[idx];
signFound=true;
idx++;
}
if (signFound==true && chars[idx] < '0' && chars[idx] > '9'){
return Float.NEGATIVE_INFINITY;
}
boolean preDecimalNumFound=false;
while (idx < chars.length && Character.isDigit(chars[idx])) {
extracted+=chars[idx];
preDecimalNumFound=true;
idx++;
}
boolean decimalFound=false;
if (idx < chars.length && chars[idx]=='.') {
extracted+=chars[idx];
decimalFound=true;
idx++;
}
if (decimalFound==true && ! Character.isDigit(chars[idx])){
return Float.NEGATIVE_INFINITY;
}
boolean postDecimalNumFound=false;
while (idx < chars.length && Character.isDigit(chars[idx])) {
extracted+=chars[idx];
postDecimalNumFound=true;
idx++;
}
float fNum=Float.NEGATIVE_INFINITY;
if (preDecimalNumFound==true || postDecimalNumFound==true) {
fNum= Float.parseFloat(extracted);
}
return fNum;
}
public float stringExtractNumberAtoiWithAPI(String str) {
Pattern p = Pattern.compile("[-+]?\\d+\\.\\d+|[-+]?\\d+");
Matcher m = p.matcher(str);
String num=null; float fNum;
if (m.find()) {
num=m.group();
}
if (num !=null) {
fNum= Float.parseFloat(num);
return fNum;
}
else {
return Float.NEGATIVE_INFINITY;
}
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |