split string by char type delimiter - Android java.lang

Android examples for java.lang:String Split

Description

split string by char type delimiter

Demo Code

import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{

    public static List<String> split(String str, char delimiter) {
        int substringsCount = 1;
        for (int i = 0, len = str.length(); i < len; i++) {
            if (str.charAt(i) == delimiter) {
                substringsCount++;//from w  ww  . j ava  2s.co m
            }
        }

        if (substringsCount == 1) {
            return Collections.singletonList(str);
        }

        List<String> split = new ArrayList<String>(substringsCount);

        int index = str.indexOf(delimiter);
        int lastIndex = 0;
        while (index != -1) {

            split.add(str.substring(lastIndex, index));

            lastIndex = index + 1;
            index = str.indexOf(delimiter, lastIndex);
        }

        split.add(str.substring(lastIndex, str.length())); // add the final string after the last delimiter

        return split;
    }

}

Related Tutorials