Java String Split by Char split(String s, char sep)

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

Description

Convert a string of items separated by a separator character to an array of the items.

License

Open Source License

Parameter

Parameter Description
s string contains items separated by a separator character.
sep separator character.

Return

Array of items.

Declaration

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

Method Source Code

//package com.java2s;
/*/*from w w w .  j  a v a 2  s. co m*/
 * Copyright (C) 2004 Red Hat, 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.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import java.util.ArrayList;

public class Main {
    /**
     * Convert a string of items separated by a separator
     * character to an array of the items.  sep is the separator
     * character.  Example: Input - s == "cat,house,dog" sep==','
     * Output - {"cat", "house", "dog"}
     * @param s string contains items separated by a separator character.
     * @param sep separator character.
     * @return Array of items.
     **/
    public static String[] split(String s, char sep) {
        ArrayList al = new ArrayList();
        int start_pos, end_pos;
        start_pos = 0;
        while (start_pos < s.length()) {
            end_pos = s.indexOf(sep, start_pos);
            if (end_pos == -1) {
                end_pos = s.length();
            }
            String found_item = s.substring(start_pos, end_pos);
            al.add(found_item);
            start_pos = end_pos + 1;
        }
        if (s.length() > 0 && s.charAt(s.length() - 1) == sep) {
            al.add(""); // In case last character is separator
        }
        String[] returned_array = new String[al.size()];
        al.toArray(returned_array);
        return returned_array;
    }
}

Related

  1. split(String s, char c, int limit)
  2. split(String s, char ch)
  3. split(String s, char divider)
  4. split(String s, char divider, String[] output)
  5. split(String s, char sep)
  6. split(String splittee, String splitChar)
  7. split(String str, char c)
  8. split(String str, char c)
  9. split(String str, char ch)