Here you can find the source of split(String s, char sep)
Parameter | Description |
---|---|
s | string contains items separated by a separator character. |
sep | separator character. |
public static String[] split(String s, char sep)
//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; } }