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

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

Description

Splits the given String by the given char, vaguely similar to the <a href="http://perldoc.perl.org/functions/split.html"> Perl function 'split'</a>.

License

Open Source License

Declaration

public static final List<String> split(char c, String s) 

Method Source Code

//package com.java2s;
/*//w  w w .  java2  s  .  co  m
*   EuroCarbDB, a framework for carbohydrate bioinformatics
*
*   Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as
*   indicated by the @author tags or express copyright attribution
*   statements applied by the authors.  
*
*   This copyrighted material is made available to anyone wishing to use, modify,
*   copy, or redistribute it subject to the terms and conditions of the GNU
*   Lesser General Public License, as published by the Free Software Foundation.
*   A copy of this license accompanies this distribution in the file LICENSE.txt.
*
*   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 Lesser General Public License
*   for more details.
*
*   Last commit: $Rev: 1593 $ by $Author: hirenj $ on $Date:: 2009-08-14 #$  
*/

import java.util.List;

import java.util.ArrayList;

public class Main {
    /***************************************************
             *   
             *   Splits the given String by the given char, vaguely similar to the 
             *   <a href="http://perldoc.perl.org/functions/split.html">
             *   Perl function 'split'</a>.
             *<pre>
             *       //  returns [ "abc", "def", "", "ghi" ]
             *       split(';', "abc;def;;ghi")
             </pre>
             */
    public static final List<String> split(char c, String s) {
        List<String> strings = new ArrayList<String>();

        int start = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != c)
                continue;

            strings.add(s.substring(start, i));
            start = i + 1;
        }

        if (start <= s.length())
            strings.add(s.substring(start));

        return strings;
    }
}

Related

  1. fastSplit(final String string, final char sep)
  2. fastSplitTrimmed(final String string, final char sep)
  3. safeSplit(String string, char divider)
  4. split(char elem, String orig)
  5. split(char sep, String input)
  6. split(final String input, final char split)
  7. split(final String string, final char... toSplit)