Java String Split by Line stringSplit(String line, String delimiter)

Here you can find the source of stringSplit(String line, String delimiter)

Description

reads line from reader file and parses it on a delimiter and returns array of cells.

License

Open Source License

Parameter

Parameter Description
line the line to be split
delimiter the delimiter on which to split the string

Return

array of split string elements

Declaration

public static List<String> stringSplit(String line, String delimiter) 

Method Source Code

//package com.java2s;
// This software is licensed under the GNU General Public License,

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**// w w w.j a v  a 2s.  c o m
     * reads line from reader file and parses it on a delimiter and returns array of cells. Generally used to split a
     * comma separated set of strings into individual components
     * 
     * @param line
     *           the line to be split
     * @param delimiter
     *           the delimiter on which to split the string
     * @return array of split string elements
     */
    public static List<String> stringSplit(String line, String delimiter) {
        return stringSplit(line, delimiter, null);
    }

    /**
     * reads line from reader file and parses it on a delimiter and returns array of cells. Generally used to split a
     * comma separated set of quotes into individual components with the quotes removed
     * 
     * @param line
     *           the line to be split
     * @param delimiter
     *           the delimiter on which to split the string
     * @param trimmer
     *           to trim from each end of a string segment
     * @return array of split string elements
     */
    public static List<String> stringSplit(String line, String delimiter, String trimmer) {
        List<String> v = new ArrayList<String>(10);
        int left = 0;
        int tloc = 0;
        while ((tloc = line.indexOf(delimiter, left)) >= 0) {
            String cell = trim(line.substring(left, tloc), trimmer);
            v.add(cell);
            left = tloc + 1;
        }

        if (left < line.length() - 1) {
            // have string after last delim
            String cell = trim(line.substring(left, line.length()), trimmer);
            v.add(cell);
        }

        return v;
    }

    public static String trim(String orig, String trimmer) {
        String cell = orig;
        if (trimmer == null)
            return cell;

        if (cell.startsWith(trimmer))
            cell = cell.substring(trimmer.length(), cell.length());
        if (cell.endsWith(trimmer))
            cell = cell.substring(0, cell.length() - trimmer.length());
        return cell;
    }
}

Related

  1. splitStringPerWord(String string, int wordsPerLine)
  2. splitter(String line, char delimeter)
  3. splitToLines(CharSequence str)
  4. splitToLines(final String str)
  5. splitToPairs(String Line)