[Advanced-java] Coding String.indexOf() with ignore quoted

Nikolaos Giannopoulos nikolaos at solmar.ca
Wed Apr 2 21:18:35 2003


I coded a method similar to String.indexOf(char) except that it skips over
regions that are bound by matching quotes.  The code is below.

However, I'm not too fond of the fact that this implementation contains
method calls to get each char.  I imagine that I could further improve the
current version by grabbing a chars array of the string and operate on it
directly.

The alternate implementation that I considered was to use indexOf to
determine positions of quote chars but since I want to handle both single
and double quotes this seemed kind of wasteful (i.e. using indexOf twice at
each position) and more complex.

Assuming that the data is evenly distributed - Which approach is better in
terms of general performance?

Is there another better approach (that I am not considering)?

  public static final int indexOfIgnoreQuoted(String s, char ch, int
fromIndex) {
    int i, j = s.length();
    char c;

    if (fromIndex < 0) {
      fromIndex = 0;
    }
    if (fromIndex < j) {
      i = fromIndex;
      while (i < j) {
        c = s.charAt(i);
        switch (c) {
          case '"':
          case '\'':
            i++;
            while (i < j) {
              if (s.charAt(i++) == c)
                break;
            }
            break;
          default:
            if (c == ch)
              return (i);
            i++;
        }
      }
    }
    return (-1);
  }

--Nikolaos