Learn How to Find All Numbers in a String in Java
Find All Numbers in a String in Java
If you need to find all the numbers in a String in Java, there are several methods to accomplish this task. The most straightforward way is to use a combination of the Character class's isDigit() method with either a for-loop or a while-loop. This will allow you to test each character in the String and determine if it is a number or not. Once you have identified all of the digits, you can store them in an array or a List.
Let's take a look at a sample String that we want to search through:
String str = "This string contains 123456789 numbers";
Now we can use a for-loop to search through the String for all numbers:
int[] numbers = new int[str.length()]; int index = 0; for(int i = 0; i < str.length(); i++) { if(Character.isDigit(str.charAt(i))) { numbers[index] = Character.getNumericValue(str.charAt(i)); index++; } }
We can also use a while-loop to search through the String:
int[] numbers = new int[str.length()]; int index = 0; int i = 0; while(i < str.length()) { if(Character.isDigit(str.charAt(i))) { numbers[index] = Character.getNumericValue(str.charAt(i)); index++; } i++; }
Once we have determined the numbers in the String, we can store them in an array or a List, depending on what we need to do with them. For example, if we needed to sum the values, we could store them in a List and use the List's stream().mapToInt().sum() method to calculate their sum.
In this tutorial, we looked at several ways to find all the numbers in a String in Java. We used the Character class's isDigit() and getNumericValue() methods along with either a for-loop or a while-loop to search through the String and identify all of the numbers. We also discussed how we can store those numbers in either an array or a List, depending on what we need to do with them.