Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fixed last CS

...

Wiki Markup
This noncompliant code example attempts to trim leading charactersletters from the {{string}}. It fails to accomplish this task because {{Character.isLetter()}} does not work for supplementary and combining characters. \[[Hornig 07|AA. Java References#Hornig 07]\] (sic)

...

Code Block
bgColor#FFcccc
// Fails for combining characters
public static String trim_bad2(String string) {
  int ch;
  for (int i = 0; i < string.length(); i += Character.charCount(ch)) {
    int ch = string.codePointAt(i);
    if (!Character.isLetter(ch)) {
      break;
    }
  }
  
  return string.substring(i);
}

...

Code Block
bgColor#ccccff
public static String trim_good(String string) {
  BreakIterator iter = BreakIterator.getCharacterInstance();
  iter.setText(string);
  for (int i = iter.first(); i != BreakIterator.DONE; i = iter.next()) {
    int ch = string.codePointAt(i);
    if (!Character.isLetter(ch)) {
      break;
    }
    
  }
  
  if (i == BreakIterator.DONE) { // Reached first or last text boundary
 has been reached
 return ""; // The input  return "";
  was either blank or had only (leading) letters
  } else {
      return string.substring(i);
    }
  }
  return string;
}

To perform locale-sensitive String comparisons for searching and sorting, use the java.text.Collator class.

Risk Assessment

Failure Failing to account for supplementary and combining characters can lead to unexpected behavior.

...