Reputation: 1
I receive strings of the form "0000A", "00000000A", "0A". They can have many or no leading zeros. I want them to evaluate as equal ignoring the leading zeros. What is the best way to do this?
Upvotes: 0
Views: 972
Reputation: 120526
To avoid buffer copies by a regex engine, you can check whether one string is a suffix of the other using regionMatches
and then check that the prefix of the longer is all zeroes.
if (a.regionMatches(
Math.max(0, a.length() - b.length()),
b, Math.max(0, b.length() - a.length()),
Math.min(a.length(), b.length())) {
// Check whether the prefix that is not common to both is all zeroes.
}
Upvotes: 0
Reputation: 533680
To expand on @matt b's suggestion, you can do
if(text1.replaceAll("^0+","").equals(text2.replaceAll("^0+",""))
Upvotes: 3
Reputation: 139971
Upvotes: 1