split function that supplement the default String.split method that does not allow returning an empty split. - Java java.lang

Java examples for java.lang:String Split

Introduction

The following code shows how to implement the generic split function that supplement the default String.split method that does not allow returning an empty split.

Demo Code

//package com.java2s;

import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String content = "java2s.com";
        String delim = ".";
        System.out.println(split(content, delim));
    }//from w  ww  .  jav  a2 s  . c  o  m

    /**
     * <p>Method that implement the generic split function that supplement
     * the default String.split method that does not allow returning
     * an empty split.</p>
     * @param content content to be split
     * @param delim delimiter used for breakdown content
     * @return list of segments delimited by the delimiter.
     */
    public static List<String> split(final String content,
            final String delim) {
        List<String> splits = null;

        if (content != null && delim != null) {
            splits = new LinkedList<String>();
            String cursor = content;
            int delimLen = delim.length();
            int indexDelim = -1;

            while (true) {
                indexDelim = cursor.indexOf(delim);
                if (indexDelim == -1) {
                    splits.add(cursor);
                    break;
                }
                splits.add(cursor.substring(0, indexDelim));
                cursor = cursor.substring(indexDelim + delimLen);
            }
        }

        return splits;
    }
}

Related Tutorials