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)
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)
You can use the StringUtils class from Apache Commons Lang like this:
StringUtils.stripStart(yourString,"0");
removing leading zeroes from text variable | OutSystems
Remove Leading Zeros with NumberFormat
apex - Removing leading zeroes in Date String - Salesforce Stack Exchange
How to remove leading zeros from Strings in java - Stack Overflow
If you really want a locally formatted date, you can use Date.parse and Date.format:
String shipDate = '04/06/2022';
System.debug(Date.parse(shipDate).format());
However, be aware that Date.parse depends on the user locale, and the format method also depends on the user locale. In other words, this answer will only work if the date is formatted in the correct locale for the user.
A more literal interpretation, we can split, format, and join, like this:
String shipDate = '04/06/2022';
String[] values = shipDate.split('/');
for(Integer i = 0; i < values.size(); i++) {
values[i] = Integer.valueOf(values[i])+'';
}
System.debug(String.join(values,'/'));
For a Regular Expression approach, you can use:
String shipDate = '04/06/2022';
// Option 1:
shipDate = shipDate.replaceAll('\\b0(\\d)','$1');
// Option 2:
shipDate = shipDate.replaceAll('\\b0','');
System.debug(shipDate);
Note that if a Regular Expression wants an escaped character, such as \b or \d, you need to escape it again, because that's also Apex's escape character. This is why you see \\b and \\d in the example above.
Also note that Apex's Regular Expression format is closer to Java, not JavaScript, so /.../g doesn't actually do a global search, but just tries to match those characters. To enable the "g" flag, you have to do something like '(?g)\\b0' instead. Regardless, you don't need to, because replaceAll implies g.
You'll want to read Java's Pattern documentation for more information.
The formatting of date is best done via DateTime.format(...):
Converts the date to the specified time zone and returns the converted date as a string using the supplied Java simple date format.
Unfortunately converting a String such as 04/06/2022 into DateTime runs into a problem: neither Date nor DateTime support arbitrary formats for parsing. They assume you'll present a String in the current user's locale. While this is certainly doable for a well-known, fixed locale, in a more general case this becomes cumbersome. JSON to the rescue!
In JSON, the date/time format is not standardized...but it is standardized in JavaScript via ISO 8601. Many JSON implementations follow the "JSON is JavaScript" dogma and adopt ISO 8601 format as a best practice/convention:
Date: 2022-04-13 Date and time in UTC:
- 2022-04-13T18:26:19+00:00
- 2022-04-13T18:26:19Z
- 20220413T182619Z
Salesforce's JSON serialization/deserialization engine happens to use ISO 8601. The timezone does matter when you're dealing with string/date conversion. If you omit the timezone, results can be confusing. This example does everything in GMT:
String shipDate = '04/06/2022'; // assume GMT
String[] shipDate_parts = shipDate.split('/');
String shipDate_iso8601 = String.format(
'{0}-{1}-{2}T00:00:00Z', // YYYY-MM-DD:..
new List <Object> {
shipDate_parts[2],
shipDate_parts[0],
shipDate_parts[1]
});
DateTime dt = (DateTime) JSON.deserialize('"' + shipDate_iso8601 + '"', DateTime.class);
String shipDateWithoutZeros = dt.format('M/d/yyyy', 'GMT');
System.debug(shipDate + ' -> ' + dt + ' -> ' + shipDateWithoutZeros);
prints
04/06/2022 -> 2022-04-06 00:00:00 -> 4/6/2022
to the debug log
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.
If you want to use a regex based approach, then one option would be to greedily remove all zeroes, starting from the beginning, so long as we do not replace the final character in the string. The following pattern does this:
^0+(?=.)
The lookahead ensures that there is at least one digit remaining, hence, a final zero will never be replaced.
String input1 = "040008";
String input2 = "000008";
String input3 = "000000";
input1 = input1.replaceAll("^0+(?=.)", "");
input2 = input2.replaceAll("^0+(?=.)", "");
input3 = input3.replaceAll("^0+(?=.)", "");
System.out.println(input1);
System.out.println(input2);
System.out.println(input3);
40008
8
0
Demo
By the way, I like the answer by @camickr and you should consider that as an option.
For those thinking, I want a quick solution to this problem.Here's the complete solution to this problem, but this is not a college assignment where I'd copy-paste answers to submit as fast as possible. I am learning for myself, for myself to build programming logic. https://github.com/MdRubelRana/Solution-of-all-problem-from-Y.-Daniel-Liang-10th-edition/blob/master/Chapter%2003/Chapter%2003%20Problem%2009%20(Business%20check%20ISBN-10).java
Let's start my question.
I create a variable to store ISBN9. And another one to save that variable as ISBN9 variable will get manipulated later. Say that variable is saved_ISBN9.
Then, I find d9,d8...d1 accordingly, correctly. In the same time, I manipulate the ISBN9 variable to get the remaining ISBN9.
I calculated checksum.
Finally, I want to concatentate ISBN9 with its checksum. Here's where the issue occurred.
if (checkSum == 10) {
checkSumStr = "X";
} else {
checkSumStr = Integer.toString(saved_ISBN9);
}I am losing the leading zeroes in integer as integer never really has "leading" zeroes, as per se. Is there anyway to not drastically change my program logic and still preserve leading zeroes while converting to string?
Hi all,
let's say i have a list
result = [0, 0, 4, 5, 1, 3]
and i want to remove the leading zeroes from that list.
here is my code, is it pythonic?
for i in range(len(result)):
if result[i] != 0:
result = result[i:]
breakthis is part of the exercise, in the book 'Elements of programming interviews' i found code that is more complicated and i tottaly don't get it (but it works)
result = result[next((i for i, x in enumerate(result) if x != 0),
len(result)):] or [0]can someone explain me this? this is the best way to make it? I have read about next() function and i get that in the end this is result = result[2:].