Java String Split by Line split(String line, char delimiter)

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

Description

Splits the row into separate cells based on the delimiter character.

License

Open Source License

Parameter

Parameter Description
line the row to split
delimiter the delimiter to use

Return

the cells

Declaration

public static String[] split(String line, char delimiter) 

Method Source Code

//package com.java2s;
/*/*  w ww  .ja  v  a  2  s .  c o  m*/
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;

public class Main {
    /**
     * Splits the row into separate cells based on the delimiter character.
     * String.split(regexp) does not work with empty cells (eg ",,,").
     *
     * @param line   the row to split
     * @param delimiter   the delimiter to use
     * @return      the cells
     */
    public static String[] split(String line, char delimiter) {
        return split(line, "" + delimiter);
    }

    /**
     * Splits the row into separate cells based on the delimiter string.
     * String.split(regexp) does not work with empty cells (eg ",,,").
     *
     * @param line   the row to split
     * @param delimiter   the delimiter to use
     * @return      the cells
     */
    public static String[] split(String line, String delimiter) {
        ArrayList<String> result;
        int lastPos;
        int currPos;

        result = new ArrayList<>();
        lastPos = -1;
        while ((currPos = line.indexOf(delimiter, lastPos + 1)) > -1) {
            result.add(line.substring(lastPos + 1, currPos));
            lastPos = currPos;
        }
        result.add(line.substring(lastPos + 1));

        return result.toArray(new String[result.size()]);
    }
}

Related

  1. split(String aLine, char delimiter, char beginQuoteChar, char endQuoteChar, boolean retainQuotes, boolean trimTokens)
  2. split(String line)
  3. split(String line)
  4. split(String line)
  5. split(String line)
  6. split(String line, char delimiter)
  7. split(String line, String delimiter)
  8. split(String line, String regex)
  9. split(String line, String separator)