2012-02-25 22 views
1

我想用一個ID生成一個String11數字。
例如: 與ID=12帳戶會給00000000012簡單函數java到內容/反向的字符串

此後,我需要檢索從字符串此ID。

例如: 與00000000022字符串給出ID=22

+0

爲什麼的ID必須是相同的長度? – 2012-02-25 04:01:48

回答

7

格式字符串,使用String.format

int n = 123; 
String.format("%011d", 123); 
// ===> 0000000

要獲得數字符串後面,使用Integer.parseInt

Integer.parseInt("00000000123"); 
// ====> 123 
+0

這是工作:)我不知道這個功能謝謝 – socrateisabot 2012-02-25 04:06:47

+0

當然,很樂意幫忙! – 2012-02-25 04:09:57

0

正如從String到int的其他答案中提到的那樣,使用Integer.parseInt()

然而,用於創建字符串我建議:

for(int x=0;x<10;x++){ 
    thestring="0"+thestring; 
} 

你需要多少個零取代10。

你也可以使用java.text.DecimalFormat,你的選擇。

或者結合了:

int lengthID=10; 
String zeros=""; 
for(int x=0;x<lengthID;x++){ 
    zeros="0"+zeros; 
} 
java.text.DecimalFormat id=new java.text.DecimalFormat(zeros); 
+0

thestring =「0」+ thestring;非常昂貴 – 2012-02-25 06:23:39