[英]Remove X Character occurence from Starting of string until Different Character Not found in Java
I am stuck in problem and not find Solution please help me to resolve it.我陷入了问题,找不到解决方案,请帮我解决它。 Below is code
下面是代码
String number = "000097127073653";
Boolean isOtherDigitFound = false;
int i=0;
for(int x=0 ; x<nunber.toCharArray() ; x++){
if(number.toChatArray()[x] != 0 && !isOtherDigitFound ){
isOtherDigitFound=true;
i=x;
}
}
number = number.subStr(x,number.length);
System.out.print(number);
I got the output that i wants which is 97127073653 But there is some easy way to do this.我得到了我想要的 output,它是 97127073653 但是有一些简单的方法可以做到这一点。
I want to remove all occurence of 0 from Starting of string.but not from middle or somewhere else.我想从字符串的开头删除所有出现的 0。但不是从中间或其他地方。
Example:- I have Number like 0000123400022 then output should be like 123400022示例:- 我有像 0000123400022 这样的数字,然后 output 应该像 123400022
Please help me请帮我
Thanks in advance提前致谢
For example, the above code to work may look like this例如,上面的代码可能看起来像这样
String number = "0000123400022";
Boolean isOtherDigitFound = false;
int i = 0;
for (int x = 0; x < number.length(); x++) {
if (number.charAt(x) != '0' && !isOtherDigitFound) {
isOtherDigitFound = true;
i = x;
break;
}
}
number = number.substring(i, number.length());
System.out.print(number);
You could use replaceAll
method in Java's String
class.您可以在 Java 的
String
class 中使用replaceAll
方法。
number = number.replaceAll("^0+", ""));
by adding ^
in replaceAll
method replaces the leading characther and by adding $
the trailing characters are replaced.通过在
replaceAll
方法中添加^
替换前导字符,并通过添加$
替换尾随字符。 So if you want to replace the trailing 0 values of the string you can do number.replaceAll("0+$", "");
因此,如果要替换字符串的尾随 0 值,可以执行
number.replaceAll("0+$", "");
Now you may rewrite your code to simply three lines现在您可以将代码重写为简单的三行
String number = "000097127073653";
number = number.replaceAll("^0+", ""));
System.out.print(number);
I'll do it something like this.我会做这样的事情。 Hope it's easy enough to understand.
希望它很容易理解。
public String removingLeadingZero(final String number) {
if (StringUtils.isEmpty(number)) {
return number;
}
int i = 0;
while (number.charAt(i) == '0') { // Here'0' can be replaced with any charater you want
i++;
}
return number.substring(i);
}
If your strings are regular numbers (not containing any chars or non-numerical values), you could just cast your string to long and back.如果您的字符串是常规数字(不包含任何字符或非数字值),您可以将字符串转换为 long 并返回。 This will automatically remove all starting zeros.
这将自动删除所有起始零。
String frontTrimmed = Long.parseLong(stringValue, 10) + "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.