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

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

Description

split

License

Open Source License

Declaration

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

Method Source Code

//package com.java2s;
/**// ww  w . jav a 2s  .c  o  m
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library 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 Lesser General Public License for more
 * details.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    private static final String[] _emptyStringArray = new String[0];

    public static String[] split(String s, char delimiter) {
        s = s.trim();

        if (s.isEmpty()) {
            return _emptyStringArray;
        }

        List<String> values = new ArrayList<>();

        int offset = 0;
        int pos = s.indexOf(delimiter, offset);

        while (pos != -1) {
            values.add(s.substring(offset, pos));

            offset = pos + 1;
            pos = s.indexOf(delimiter, offset);
        }

        if (offset < s.length()) {
            values.add(s.substring(offset));
        }

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

    public static String[] split(String s, String delimiter) {
        if ((delimiter == null) || delimiter.equals("")) {
            return _emptyStringArray;
        }

        s = s.trim();

        if (s.equals(delimiter)) {
            return _emptyStringArray;
        }

        if (delimiter.length() == 1) {
            return split(s, delimiter.charAt(0));
        }

        List<String> nodeValues = new ArrayList<>();

        int offset = 0;
        int pos = s.indexOf(delimiter, offset);

        while (pos != -1) {
            nodeValues.add(s.substring(offset, pos));

            offset = pos + delimiter.length();
            pos = s.indexOf(delimiter, offset);
        }

        if (offset < s.length()) {
            nodeValues.add(s.substring(offset));
        }

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

Related

  1. split(String input, String... delimiters)
  2. split(String inputStr, String delimeter, String enclosureStr)
  3. split(String s, char delim)
  4. split(String s, char delim)
  5. split(String s, char delimiter)
  6. split(String s, char delimiter)
  7. split(String s, char delimiter)
  8. split(String s, String delim)
  9. split(String s, String delim)