Java String Split by Delimiter split(String str, String delim)

Here you can find the source of split(String str, String delim)

Description

Splits the given string into chunks.

License

Open Source License

Parameter

Parameter Description
str string to split into chunks.
delim the delimeter to use for splitting.

Return

array with the individual chunks.

Declaration

public static String[] split(String str, String delim) 

Method Source Code

//package com.java2s;
/*//  w  w w.  ja v a 2  s . co m
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 */

import java.util.ArrayList;
import java.util.List;

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

    /**
     * Splits the given string into chunks.
     *
     * @param str string to split into chunks.
     * @param delim the delimeter to use for splitting.
     *
     * @return array with the individual chunks.
     *
     * @since 1.0b8
     */
    public static String[] split(String str, String delim) {
        int startOffset = 0;
        int endOffset = -1;
        int sepLength = delim.length();
        List lines = new ArrayList(15);

        while ((endOffset = str.indexOf(delim, startOffset)) > -1) {
            lines.add(str.substring(startOffset, endOffset));
            startOffset = endOffset + sepLength;
        }

        if (startOffset > 0) {
            lines.add(str.substring(startOffset));
        } else {
            lines.add(str);
        }

        return (String[]) lines.toArray(EMPTY_STRING_ARRAY);
    }

    /**
     * Returns the index within the given string of the <em>x.</em> occurrence of the
     * specified character.
     *
     * @param character character to search.
     * @param str the string to search.
     * @param x <em>x.</em> occurrence of the character to search for.
     *
     * @return s the index within the given string of the <em>x.</em> occurrence of the
     *         given character. Returns <code>-1</code> if the specified character is
     *         not contained in the given string or it occurs less than the specified
     *         occurrence to look for.
     */
    public static int indexOf(char character, String str, int x) {
        for (int i = 1, pos = -1; (pos = str.indexOf(character, pos + 1)) > -1; i++) {
            if (i == x) {
                return pos;
            }
        }

        return -1;
    }
}

Related

  1. split(String str, int delim, String trailing)
  2. split(String str, String delim)
  3. split(String str, String delim)
  4. split(String str, String delim)
  5. split(String str, String delim)
  6. split(String str, String delim)
  7. split(String str, String delimeter)
  8. split(String str, String delimiter)
  9. split(String str, String delimiter)