I Have string like so: "He3llo5"
How do I strip this String so that only the numbers remain?
Desired result:
35
I Have string like so: "He3llo5"
How do I strip this String so that only the numbers remain?
Desired result:
35
Simplest solution: use a regex and .replaceAll():
String string="He3llo5";
String result = string.replaceAll("[^\\d.]", "");
System.out.println(result);
See this code execute at Ideone.com.
35
Alternatively, you could write your own method which utilizes Character.isDigit() and a StringBuilder like so:
public static String stripAlphabet(String s) {
int len = s.length();
StringBuilder str = new StringBuilder();
for(int i = 0; i < len; i++) {
char c = s.charAt(i);
str.append(Character.isDigit(c) ? c : "");
}
return str.toString();
}
The following also produces 35 as the result:
String string="He3llo5";
String result = stripAlphabet(string);
System.out.println(result);
You can use the Pattern Example
Pattern intsOnly=Pattern.compile("\\d+");
Matcher make=intsOnly.matcher(string);
make.find();
string=make.group();
Integer.parseInt(
"He3ll5"
.codePoints()
.filter( Character :: isDigit )
.collect(
StringBuilder :: new ,
StringBuilder :: appendCodePoint ,
StringBuilder :: append
)
.toString()
)
See this code run live at Ideone.com.
35
Loop through each character’s Unicode code point number, asking if that code point represents a character that is a digit. If so, collect that code point or its conversion to a String.
Calling String#codePoints gives us an IntStream, a stream of the code point integer numbers.
We filter out the letters by calling Character#IsDigit. We collect the remaining digit characters into a StringBuilder.
From the string of digits, we parse as an int by calling Integer.parseInt.
String input = "He3llo5";
IntStream codePoints = input.codePoints();
String digits =
codePoints
.filter( Character :: isDigit )
.collect( StringBuilder :: new ,
StringBuilder :: appendCodePoint ,
StringBuilder :: append )
.toString();
int result = Integer.parseInt( digits );
result = 35
charBe aware that the char type in Java is obsolete. That type fails to represent even half of the characters defined in Unicode. Use code point integers instead of char.