seth
seth

Reputation: 1

Comparison Ignoring Leading Characters

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

Answers (3)

Mike Samuel
Mike Samuel

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

Peter Lawrey
Peter Lawrey

Reputation: 533680

To expand on @matt b's suggestion, you can do

if(text1.replaceAll("^0+","").equals(text2.replaceAll("^0+",""))

Upvotes: 3

matt b
matt b

Reputation: 139971

  1. remove any leading zeros
  2. test the equality of the remaining strings

Upvotes: 1

Related Questions