split string to list by length and encoding - Android java.lang

Android examples for java.lang:String Split

Description

split string to list by length and encoding

Demo Code

import android.graphics.Paint;
import java.util.ArrayList;
import java.util.List;

public class Main{

    public static List<String> split(String text, int length,
            String encoding) throws Exception {
        List texts = new ArrayList();
        int pos = 0;
        int startInd = 0;

        for (int i = 0; (text != null) && (i < text.length());) {
            byte[] b = String.valueOf(text.charAt(i)).getBytes(encoding);
            if (b.length > length) {
                ++i;//  ww w.ja v  a 2 s.  c  o m
                startInd = i;
                break;
            }

            pos += b.length;
            if (pos >= length) {
                int endInd;
                if (pos == length)
                    endInd = ++i;
                else {
                    endInd = i;
                }

                texts.add(text.substring(startInd, endInd));
                pos = 0;
                startInd = i;
                break;
            }
            label114: ++i;
        }

        if (startInd < text.length())
            texts.add(text.substring(startInd));

        return texts;
    }

}

Related Tutorials