Java String Split by Delimiter split(String value, String[] delimiters)

Here you can find the source of split(String value, String[] delimiters)

Description

Splits a string into substrings using a delimiter array.

License

Open Source License

Parameter

Parameter Description
value string to be tokenized
delimiters array of delimiters

Return

array of tokens

Declaration

public static String[] split(String value, String[] delimiters) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/* ww  w. ja  va2s .  com*/
 * IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;

public class Main {
    /**
     * Splits a string into substrings using a delimiter array.
     * 
     * @param value
     *            string to be tokenized
     * @param delimiters
     *            array of delimiters
     * @return array of tokens
     */
    public static String[] split(String value, String[] delimiters) {
        ArrayList result = new ArrayList();
        int firstIndex = 0;
        int separator = 0;
        while (firstIndex != -1) {
            firstIndex = -1;
            for (int i = 0; i < delimiters.length; i++) {
                int index = value.indexOf(delimiters[i]);
                if (index != -1 && (index < firstIndex || firstIndex == -1)) {
                    firstIndex = index;
                    separator = i;
                }
            }
            if (firstIndex != -1) {
                if (firstIndex != 0) {
                    result.add(value.substring(0, firstIndex));
                }
                int newStart = firstIndex + delimiters[separator].length();
                if (newStart <= value.length()) {
                    value = value.substring(newStart);
                }
            } else if (value.length() > 0) {
                result.add(value);
            }
        }
        return (String[]) result.toArray(new String[0]);
    }
}

Related

  1. split(String text, String delimiter)
  2. split(String value, char delim)
  3. split(String value, char delimiter)
  4. split(String value, String delimiter)
  5. split(String value, String delimiter)
  6. split(String what, char delim)
  7. split(String[] srcArray, String delimiterRegExp)
  8. split2(String string, String delimiter)
  9. splitAll(String str, String delim)