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

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

Description

split

License

Open Source License

Declaration

public static String[] split(String s, char c, int limit) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

public class Main {
    public static String[] split(String s, char c, int limit) {
        if (s == null) {
            return null;
        }/*from   w  w w . j a  v a  2 s  .co m*/
        ArrayList<Integer> pos = new ArrayList<Integer>();
        int i = -1;
        while ((i = s.indexOf((int) c, i + 1)) > 0) {
            pos.add(i);
        }
        int n = pos.size();
        int[] p = new int[n];
        i = -1;
        for (int x : pos) {
            p[++i] = x;
        }
        if ((limit == 0) || (limit > n)) {
            limit = n + 1;
        }
        String[] result = new String[limit];
        if (n > 0) {
            result[0] = s.substring(0, p[0]);
        } else {
            result[0] = s;
        }
        for (i = 1; i < limit - 1; ++i) {
            result[i] = s.substring(p[i - 1] + 1, p[i]);
        }
        if (limit > 1) {
            result[limit - 1] = s.substring(p[limit - 2] + 1);
        }
        return result;
    }
}

Related

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