Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





Java - Code Samples

 Sample 1. Get Length of String having UTF8 Characters

public static int utf8Length(String string) {
   CharacterIterator iter = new StringCharacterIterator(string);
   char ch = iter.first();
   int size = 0;
   while (ch != CharacterIterator.DONE) {
      if ((ch >= 0xD800) && (ch < 0xDC00)) {
         char trail = iter.next();
         if ((trail > 0xDBFF) && (trail < 0xE000)) {
            size += 4;
         } else {
            size += 3;
            iter.previous(); // rewind one
         }
      } else if (ch < 0x80) {
         size++;
      } else if (ch < 0x800) {
         size += 2;
      } else {
         size += 3;
      }
      ch = iter.next();
   }
   return size;
}

   Like      Feedback     UTF8 characters  CharacterIterator.DONE  CharacterIterator  StringCharacterIterator



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner