Java String Split by Delimiter split(String str, char delimiter)

Here you can find the source of split(String str, char delimiter)

Description

Splits a string into substrings based on the supplied delimiter character.

License

Open Source License

Parameter

Parameter Description
str The string to split
delimiter The character that delimits the string

Return

A string array containing the resultant substrings

Declaration

public static final List split(String str, char delimiter) 

Method Source Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**//  w  w  w. j  a  va2s  .  c o  m
     * Splits a string into substrings based on the supplied delimiter
     * character. Each extracted substring will be trimmed of leading
     * and trailing whitespace.
     *
     * @param str The string to split
     * @param delimiter The character that delimits the string
     * @return A string array containing the resultant substrings
     */
    public static final List split(String str, char delimiter) {
        // return no groups if we have an empty string
        if ((str == null) || "".equals(str)) {
            return new ArrayList();
        }

        ArrayList parts = new ArrayList();
        int currentIndex;
        int previousIndex = 0;

        while ((currentIndex = str.indexOf(delimiter, previousIndex)) > 0) {
            String part = str.substring(previousIndex, currentIndex).trim();
            parts.add(part);
            previousIndex = currentIndex + 1;
        }

        parts.add(str.substring(previousIndex, str.length()).trim());

        return parts;
    }
}

Related

  1. split(String str, char delim)
  2. split(String str, char delimiter)
  3. split(String str, char delimiter)
  4. split(String str, char delimiter)
  5. split(String str, char delimiter)
  6. split(String str, char delimiter, boolean trim)
  7. split(String str, int delim, String trailing)
  8. split(String str, String delim)
  9. split(String str, String delim)