get Length for UTF-8 string - Android java.lang

Android examples for java.lang:String UTF-8

Description

get Length for UTF-8 string

Demo Code

import android.content.res.AssetManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class Main{

    public static int getLength(String str) {
        try {/*from   w  w  w  . j a  v a 2 s  .c  o  m*/
            int utfLength = str.getBytes("UTF-8").length;
            String s = new String(str.getBytes(), "UTF-8");
            int length = s.length();
            int chNum = (utfLength - length) / 2;
            int lastLength = (length - chNum + 1) / 2 + chNum;
            return lastLength;
        } catch (UnsupportedEncodingException e1) {
        }
        return 0;
    }

}

Related Tutorials