Get array of substrings Between separators - Java java.lang

Java examples for java.lang:String Substring

Description

Get array of substrings Between separators

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com java2s.com java2s.com java2s.com";
        String open = "o";
        String close = "m";
        System.out.println(java.util.Arrays.toString(substringsBetween(str,
                open, close)));/*www .ja va2  s  . com*/
    }

    public static String[] substringsBetween(String str, String open,
            String close) {
        if (str == null || isEmpty(open) || isEmpty(close)) {
            return null;
        }
        int strLen = str.length();
        if (strLen == 0) {
            return new String[0];
        }
        int closeLen = close.length();
        int openLen = open.length();
        List<String> list = new ArrayList<String>();
        int pos = 0;
        while (pos < strLen - closeLen) {
            int start = str.indexOf(open, pos);
            if (start < 0) {
                break;
            }
            start += openLen;
            int end = str.indexOf(close, start);
            if (end < 0) {
                break;
            }
            list.add(str.substring(start, end));
            pos = end + closeLen;
        }
        if (list.isEmpty()) {
            return null;
        }
        return list.toArray(new String[list.size()]);
    }

    public static String toString(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    public static String toString(Object obj, String nullStr) {
        return obj == null ? nullStr : obj.toString();
    }

    public static boolean isEmpty(String chkStr) {
        if (chkStr == null) {
            return true;
        } else {
            return "".equals(chkStr.trim()) ? true : false;
        }
    }
}

Related Tutorials