Hello Folks,
As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to extract numbers from a string.
Write a JAVA program for below requirements:
- Take an alphanumeric string from user.
- Verify if it is alphanumeric.
- If it is alphanumeric, extract all numbers present in string.
- Add all numbers and print it.
JAVA Program:
import java.util.Scanner; import org.apache.commons.lang3.StringUtils; public class ExtractNumbersFromString { public static void main(String[] args) { int sum = 0; // Reading input from user Scanner sc = new Scanner(System.in); System.out.println("Please enter the alphanumeric string:"); String inputByUser = sc.nextLine(); System.out.println("String entered by user: " + inputByUser); // Check if input string is alphanumeric Using regex boolean flagRegex = inputByUser.matches("([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*"); // if string is alphanumeric, extract char and check if it is digit if (flagRegex == true) { for (int i = 0; i < inputByUser.length(); i++) { char c = inputByUser.charAt(i); if (Character.isDigit(c)) sum = sum + Character.getNumericValue(c); } System.out.println("Sum of numbers found in " + inputByUser + " :" + sum); } else { System.out.println(inputByUser + " is not an alphanumeric."); } } }
Output:
[java]
Please enter the alphanumeric string:
hfghfgh54545
String entered by user: hfghfgh54545
Sum of numbers found in hfghfgh54545 :23
==================================================================
Please enter the alphanumeric string:
%^&%dhfjf78
String entered by user: %^&%dhfjf78
%^&%dhfjf78 is not an alphanumeric.
[/java]
#HappyCoding
Thanks for the share
[a-zA-Z]+[0-9]+[A-Za-z0-9]* should be the regular expression to get an alphanumeric which actually has some numbers in it . If there is no number then it will return false
boolean flagRegex = inputByUser.matches(“([A-Za-z]+[0-9]+[A-Za-z0-9]*”);
I feel we also can do this without even using regex:
package javapractice;
import java.util.Scanner;
public class ExtractNumbersFromString {
public static void main(String[] args) {
int sum=0;
// Reading input from user
Scanner sc= new Scanner(System.in);
System.out.println(“Please enter the alphanumeric string:”);
String inputByUser= sc.nextLine();
System.out.println(“String entered by user: “+inputByUser);
for(int i=0;i<inputByUser.length();i++)
{
char c= inputByUser.charAt(i);
if(Character.isDigit(c))
sum=sum+ Character.getNumericValue(c);
if(sum!=0){
System.out.println("Sum of numbers found in "+inputByUser +" :"+sum);
}
else
{
System.out.println(inputByUser+" is not an alphanumeric.");
}
}
}
Hi,
I am verifying in beginning if input is alphanumeric. You are verifying in last. That is difference.
@Raji: This is wrong for Test data as Test00Test. Output should be zero but your code will print “is not an alphanumeric”.
Thanks. I will explain more.
Thanks for the share
2 things here
FYI
1) to use String.utils we need to have Apache lang library added in the project
Below code is not correct
2)boolean flagRegex= inputByUser.matches(“[a-zA-Z0-9]+”);
if you have a string whcih just has alphabets like ‘udzialMeansShare’ , it will return true i.e. its an alphanumeric and else portion will never be executed
you can make the below changes
boolean flagRegex= inputByUser.matches(“[a-zA-Z]+”); // this will return true only if we have a string which does not have characters
so we can do if ( !flagRegex)
Actually I was trying to write regex to verify alphanumeric if string has alphabets and numbers both. StringUtils and regex are giving true if string contains only characters also. Main focus is to extract numbers as of now. I will update code once i writw proper regex.
okies. Because Alphanumeric means it can have alphabets and numbers. But its not must that it should have both numbers and alphabets..
Yes but I wanted both in string. I updated regex.
Hi Amod,
I tried like below
public class NumbersInString2 {
public static void main(String[] args) {
int count = 0;
String s = “jisncansjkcna33wqsnfjks732hjsddh71”;
String str[] = s.split(“[a-zA-Z]+”);
for (int i = 1; i < str.length; i++) {
count = count + Integer.parseInt(str[i]);
}
System.out.println(str[0]+" : "+count);
}
}
Output
: 836
My question here is we are splitting given string by numbers and there are 3 numbers in it i.e, 33,732,71 so why str[0] is "" (Empty String). its working fine if start the loop using 1.
That’s the way split method works.
Code 1:
String str1 [] = “amod123”.split(“m”);
System.out.println(“Length: “+str1.length);
for(int i=0;i
Thanks