[英]How to remove leading zeros from numeric text?
我用它來從我的輸入字符串中刪除前導零。
return a.replaceAll("^0+","");
但是上面的字符串甚至可以刪除任何字母數字字符串。 我不想那樣做。 我的要求是:
只應刪除數字的前導零,例如
00002827393 -> 2827393
如果您有字母數字編號,則不得刪除前導零
000ZZ12340 -> 000ZZ12340
您可以檢查您的字符串是否僅由數字組成:
Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(a);
if(m.matches()){
return a.replaceAll("^0+", "");
} else {
return a;
}
另外:
你也可以試試這個:
a.replaceAll("^0+(?=\\d+$)", "")
請注意,正向前瞻(?=\\\\d+$)
檢查字符串的其余部分(在起始0
之后,與^0+
匹配)在匹配/替換任何內容之前僅由數字組成。
System.out.println("00002827393".replaceAll("^0+(?=\\d+$)", ""));
System.out.println("000ZZ12340".replaceAll("^0+(?=\\d+$)", ""));
2827393 000ZZ12340
測試傳入的字符串是否與數字模式“\\ d +”匹配。 “\\ d”是數字的字符類 。 如果是數字,則將調用結果返回到replaceAll
,否則只返回原始字符串。
if (str.matches("\\d+"))
return str.replaceAll("^0+", "");
return str;
測試:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(replaceNumZeroes("0002827393"));
System.out.println(replaceNumZeroes("000ZZ1234566"));
}
產生輸出
2827393
000ZZ1234566
邏輯:它將字符串轉換為char數組並從i = 0開始; 一旦它擊中第一個數字值,它就會從for循環中斷,一旦它到達第一個字符(1到9除外),它就會返回相同的字符串。 在第一個for循環之后,我們考慮以下情況:
case 1. 00000000000
case 2. 00000011111
case 3. 11111111111
如果它是1或3(即來自第一個for循環的i的值將是0或字符串的長度)case,那么只返回字符串。 否則從char數組復制到一個新的char數組,從i的值開始(i的值將從第一個for循環得到,它保存第一個數值位置。)。 希望它清除。
public String trimLeadingZeros(String str)
{
if (str == null)
{
return null; //if null return null
}
char[] c = str.toCharArray();
int i = 0;
for(; i<c.length; i++)
{
if(c[i]=='0')
{
continue;
}
else if(c[i]>='1' && c[i]<='9')
{
break;
}
else
{
return str;
}
}
if(i==0 || i==c.length)
{
return str;
}
else
{
char[] temp = new char[c.length-i];
int index = 0;
for(int j=i; j<c.length; j++)
{
temp[index++] = c[j];
}
return new String(temp);
}
}
我只做了以下幾點
String string = string.trim();
while(string.charAt(0) == '0'){
string = string.substring(1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.