Can't we erase this when we have a zero in front of a string of letters and numbers in Java?

Asked 2 years ago, Updated 2 years ago, 34 views

01234 -> 1234
0001234a -> 1234a
001234-a -> 1234-a
101234 -> 101234
2509398 -> 2509398
123z -> 123z
000002829839 -> 2829839

Like this, I want to erase it when there's a zero in front of me, and if it's not, I want to keep it as it is How shall I do it?

java string

2022-09-22 08:09

1 Answers

Regular expressions make it simple to solve. Since you said you wanted to erase the first zero, s.replaceFirst("^0+(?!$)", "") You can use the regular expression and replaceFirst method in this way.

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+(?!$)", "") + "]");
}

If you're curious about the regular show, http://breath91.tistory.com/entry/Java-%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D It's detailed here.


2022-09-22 08:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.