split UTF String - Java java.lang

Java examples for java.lang:String UTF

Description

split UTF String

Demo Code


//package com.java2s;

import java.util.ArrayList;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        System.out.println(java.util.Arrays.toString(splitUTFString(str)));
    }//from  w  w  w . j  av a  2s .c o  m

    public static Object[] splitUTFString(String str) {
        int strlen = str.length();
        int utflen = 0;
        int c;
        int prev = 0;
        ArrayList<String> list = new ArrayList<String>();

        /* use charAt instead of copying String to char array */
        for (int i = 0; i < strlen;) {
            c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                utflen++;
            } else if (c > 0x07FF) {
                utflen += 3;
            } else {
                utflen += 2;
            }

            if (utflen > 65535) {
                list.add(str.substring(prev, i));

                utflen = 0;
                prev = i;
            } else {
                i++;
            }
        }
        list.add(str.substring(prev));

        return list.toArray();
    }
}

Related Tutorials