我有一个Java字符串对象。我只需要从中提取数字。我举个例子:
123456-789我要123456789
是否存在只提取数字的库函数?
谢谢你的回答。在我尝试这些之前,我需要知道我是否必须安装任何额外的llibraries?
我有一个Java字符串对象。我只需要从中提取数字。我举个例子:
123456-789我要123456789
是否存在只提取数字的库函数?
谢谢你的回答。在我尝试这些之前,我需要知道我是否必须安装任何额外的llibraries?
当前回答
import java.util.*;
public class FindDigits{
public static void main(String []args){
FindDigits h=new FindDigits();
h.checkStringIsNumerical();
}
void checkStringIsNumerical(){
String h="hello 123 for the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
if(h.charAt(i)!=' '){
System.out.println("Is this '"+h.charAt(i)+"' is a digit?:"+Character.isDigit(h.charAt(i)));
}
}
}
void checkStringIsNumerical2(){
String h="hello 123 for 2the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
char chr=h.charAt(i);
if(chr!=' '){
if(Character.isDigit(chr)){
System.out.print(chr) ;
}
}
}
}
}
其他回答
使用正则表达式来匹配您的需求。
String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();
System.out.print(num);
}
我已经确定了电话号码+9(987)124124的代码。
Unicode字符占用4个字节。
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
int i=0;
while ( i< buffer.length() ) { //buffer.hasRemaining()
char chr = buffer.get(i);
if (chr=='u'){
i=i+5;
chr=buffer.get(i);
}
if ( chr > 39 && chr < 58 )
result[cursor++] = chr;
i=i+1;
}
return new String( result, 0, cursor );
}
public String extractDigits(String src) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}
我受到代码肖恩·帕特里克·弗洛伊德的启发,为了获得最大的性能,我重写了它。
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
while ( buffer.hasRemaining() ) {
char chr = buffer.get();
if ( chr > 47 && chr < 58 )
result[cursor++] = chr;
}
return new String( result, 0, cursor );
}
我做性能测试非常长的字符串与最小的数字和结果是:
原始代码慢了255% 番石榴法要慢2.5-3倍 使用D+的正则表达式要慢3-3.5倍 只有D的正则表达式要慢25倍以上
顺便说一下,这取决于字符串的长度。字符串只包含6个数字是番石榴慢50%和regexp慢1倍
您可以使用正则表达式和删除非数字。
str = str.replaceAll("\\D+","");