How to remove leading zeros from alphanumeric text?
Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0"
to a blank string).
s.replaceFirst("^0+(?!$)", "")
The ^
anchor will make sure that the 0+
being matched is at the beginning of the input. The (?!$)
negative lookahead ensures that not the entire string will be matched.
Test harness:
String[] in = {
"01234", // "[1234]"
"0001234a", // "[1234a]"
"101234", // "[101234]"
"000002829839", // "[2829839]"
"0", // "[0]"
"0000000", // "[0]"
"0000009", // "[9]"
"000000z", // "[z]"
"000000.z", // "[.z]"
};
for (String s : in) {
System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}
See also
- regular-expressions.info
- repetitions, lookarounds, and anchors
String.replaceFirst(String regex)
How to remove all leading zeroes in a string
ltrim
:
$str = ltrim($str, '0');
Remove leading zero in Java
I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)
boolean allZero = true;
for (int i=0;i<value.length() && allZero;i++)
{
if (value.charAt(i)!='0')
allZero = false;
}
if (allZero)
return "0"
...The code you already have
Remove leading zeros from a number in a string
I hope this works:
try {
int i = Integer.parseInt(yourString);
System.out.println(i);
} catch(NumberFormatException e) {
// the string is not a number
}
How to remove leading zeros from Strings in java
I am aware that we can use String Utils library. But what if the String has only "0". It returns " ". Do we have any other way to remove leading 0 for all other strings except for "0".
You can create your own utility method that does exactly what you want.
Well you still haven't answered my question about whether the department can be alphanumeric or just numeric.
Based on your examples you could just convert the String to an Integer. The toString() implementation of an Integer removes leading zeroes:
System.out.println( new Integer("008").toString() );
System.out.println( new Integer("000").toString() );
System.out.println( new Integer("111").toString() );
If the string can contain alphanumeric the logic would be more complex, which is why it is important to define the input completely.
For an alphanumeric string you could do something like:
StringBuilder sb = new StringBuilder("0000");
while (sb.charAt(0) == '0' && sb.length() > 1)
sb.deleteCharAt(0);
System.out.println(sb);
Or, an even more efficient implementation would be something like:
int i = 0;
while (product.charAt(i) == '0' && i < product.length() - 1)
i++;
System.out.println( product.substring(i) );
The above two solutions are the better choice since they will work for numeric and alphanumeric strings.
Or you could even use the StringUtils class to do what you want:
String result = StringUtils.removeleadingZeroes(...) // whatever the method is
if (result.equals(" "))
result = "0";
return result;
In all solutions you would create a method that you pass parameter to and then return the String result.
Remove leading zeroes from a string
Use str::trim_start_matches
fn main() {
assert_eq!("00foo1bar11".trim_start_matches('0'), "foo1bar11");
}
Playground
How to remove leading zeros with long string
By splitting the given string into array and then remove the leading zeroes, is working fine.
where removeLeadingZeros is:
public static String removeLeading(String str) {
String regex = "^0+(?!$)";
String x[] = str.split(" ");
StringBuilder z = new StringBuilder();
for(String y:x) {
str = y.replaceAll(regex, "");
z.append(" " + str);
}
return z.toString();
}
How to remove leading and trailing zeros in a string? Python
What about a basic
your_string.strip("0")
to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip
instead (and .lstrip
for only the leading ones).
More info in the doc.
You could use some list comprehension to get the sequences you want like so:
trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]
Related Topics
Retrieve (Or Simulate) Full Query from Pdo Prepared Statement
PHP MySQL Greek Letters Showing Like? Marks
In PHP, How to Check If a Function Exists
Function Ereg_Replace() Is Deprecated - How to Clear This Bug
Pdo Error: SQLstate[Hy000]: General Error: 2031
Overwrite Line in File with PHP
How to Handle Diacritics (Accents) When Rewriting 'Pretty Urls'
PHP Strtotime +1 Month Behaviour
How to Calculate Time Difference in PHP
Interface Implementation: Declaration Must Be Compatible
How to Do Model->Where('Id', Array) Multiple Where Conditions