[英]parse non-negative doubles
我需要將字符串和整數表示非負雙精度或整數位置並返回Number或null的函數。 如果有“ +”,則返回null。
例子
2.1 , 0 -> 2.1
+2.1 , 0 -> null
-1 , 0 -> null
-1.2 , 1 -> 1.2
qwa56sdf , 3 -> 56
最優雅的方法是什么? 謝謝。
我需要這樣的代碼,但更好)
Number parse(String str, int pos){
Matcher m = Pattern.compile("^(\\d+(?:\\.\\d+)?)").matcher(str);
m.region(pos, str.length());
if(m.find()){
return Double.parseDouble(m.group());
} else {
return null;
}
}
您可以嘗試:
public static void main(String[] args) {
System.out.println(parse("2.1", 0));
System.out.println(parse("+2.1", 0));
System.out.println(parse("-1", 0));
System.out.println(parse("-1.2", 1));
System.out.println(parse("qwa56sdf", 3));
}
private static Double parse(String string, int index) {
if (string.charAt(index) == '-' || string.charAt(index) == '+') {
return null;
}
try {
return Double.parseDouble(string.substring(index).replaceAll("[^\\d.]", ""));
}
catch (NumberFormatException e) {
return null;
}
}
我不得不用replace all去除尾隨的非數字字符,因為它們引起NumberFormatException,並且對於上一個示例中的輸入將返回null。
編輯:處理類似注釋中的情況的另一種選擇可能是檢查每個字符
private static Double parse(String string, int index) {
String finalString = "";
boolean foundSeparator = false;
for (char c : string.substring(index).toCharArray()) {
if (c == '.') {
if (foundSeparator) {
break;
}
else {
foundSeparator = true;
}
}
else if (!Character.isDigit(c)) {
break;
}
finalString += c;
}
if (finalString == "") {
return null;
}
return Double.parseDouble(finalString);
}
您將需要使用String.substring()
方法的組合從String.substring()
中的指定位置開始,並使用NumberFormat
類來解析數字。
如果那在功能上是正確的,那么對我來說看起來就足夠優雅了。 您可能希望使Pattern成為最終類成員,因為您只需要編譯一次即可。 該地區可能不需要:
Matcher m = pattern.matcher(str.substring(pos));
另一個選擇是從一個1個字符長的子字符串開始,並對其進行增長,直到不再解析為止:
if ( str.charAt(pos) == '+' || str.charAt(pos) == '-' ) {
//special cases
return null;
}
Double val = null;
for ( int i = pos+1; i <= str.length(); i++ ) {
try {
val = Double.parseDouble(str.substring(pos, i)) {
} catch (NumberFormatException e) {
break;
}
}
return val;
這比較簡單,但在性能方面也很幼稚。 可讀性較差但性能更高的解決方案是在每次解析一個字符之前先自己找到double的結尾,然后再進行解析。
還有Scanner類。 專門包含用於讀取基元的方法,例如, scanner.hasNextDouble()
和scanner.nextDouble()
。 您仍然需要對+或-進行檢查,因為那仍然可以通過檢查。
public static Double parseDouble(String input, int fromIndex) {
Matcher matcher = Pattern.compile("\\d*\\.?\\d+")
.matcher(input.substring(fromIndex));
return matcher.lookingAt() ? Double.parseDouble(matcher.group()) : null;
}
我認為以下實現對於您的一組要求將更為優雅。 我正在使用java.text.NumberFormat類進行解析。
private static Number parse(String text, int position){
Number value=null;
NumberFormat nf = NumberFormat.getInstance();
try {
value = nf.parse(text,new ParsePosition(position));
if (value.intValue() < 0)
value = null;
} catch (Exception e) {
value = null;
}
return value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.