2015-10-19 61 views
1

在Java 6中,如果我有一個長度爲11的String,其中包含一個用零填充的負數並且我想將其轉換爲Long,我該如何去做這件事?將左填充的字符串轉換爲數字

String x = "000000-3946"; 

try { 
    Long.parseLong(x) 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 

...拋出一個NumberFormatException

通過刪除前導零是我得到這個工作的唯一途徑。我嘗試使用NumberFormatDecimalFormat類進行解析。

回答

2

第二屆statment將刪除所有前面的零使用正則表達式並給出一個可以解析爲Long值的有效字符串。 (可以同時處理正數和負數)

String x = "000000-3946"; 
String xWithoutLeadingZeros = x.replaceFirst("^0+", ""); 
System.out.println(Long.parseLong(xWithoutLeadingZeros)); 

從評論:

上面的代碼replaceFirst實際上會爲每個調用創建內部Pattern對象。

//code of String.replaceFirst 
return Pattern.compile(regex).matcher(this).replaceFirst(replacement); 

由於我們使用了大量的投入這種方法,創建模式對象,每次都是不正確的方法,因爲正則表達式是相同的所有投入。

所以我們只創建一次模式對象,希望它給出更好的性能結果。

private static final Pattern leadingZeroPattern = Pattern.compile("^0+"); 
private static final String EMPTY_STRING = ""; 

public static void main(String[] args) { 
    String x = "-232330000809"; 
    String xWithoutZeros = leadingZeroPattern.matcher(x).replaceFirst(EMPTY_STRING); 
    System.out.println(Long.parseLong(xWithoutZeros)); 
} 

#perfmatters

+0

如果字符串是「-1234567809」,零將被替換? – GeekyDaddy

+0

當然可以。只有前導零將被刪除。嘗試,如果你懷疑它。 – rajuGT

+0

另外我覺得,解析具有前導零的數字串,將導致模糊。因爲以零開頭的數字被認爲是八進制數字。所以,如果我們正確地修剪字符串,一切都會正常工作,看起來很好。 – rajuGT

1

首先,Long.parseLong(String)可以拋出NumberFormatException。接下來,我會檢查一個減號,如果存在,則從該位置取一個子串。喜歡的東西

String x = "000000-3946"; 
int p = x.indexOf("-") > -1 ? x.indexOf("-") : 0; 
try { 
    long l = Long.parseLong(x.substring(p)); 
    System.out.println(l); 
} catch (NumberFormatException nfe) { 
    nfe.printStackTrace(); 
} 

輸出

-3946 
0

稍微有點矯枉過正,但是這將這樣的伎倆:

final String x = "000000-3946"; 
int start = x.indexOf("-"); 

System.out.printf("%s%n", Long.parseLong(x.substring((start > -1) ? start : 0, x.length()))); 
// ...or just 
//System.out.printf("%s%n", Long.parseLong(x.substring((start > -1) ? start : 0))); 

輸出-3946

0

如果你需要一個單一的線,試試這個:

Long.parseLong(x.replaceAll("0+-", "-")) 

,並增加你的第二個問題,如果字符串是-1234567809,沒有零點在這裏更換