Get substring Between separator - Java java.lang

Java examples for java.lang:String Substring

Description

Get substring Between separator

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        String tag = "o";
        System.out.println(substringBetween(str, tag));
    }/*from w  w  w  .j a  v a 2 s .c  o  m*/

    private static final int INDEX_NOT_FOUND = -1;

    public static String substringBetween(String str, String tag) {
        return substringBetween(str, tag, tag);
    }

    public static String substringBetween(String str, String open,
            String close) {
        if (str == null || open == null || close == null) {
            return null;
        }
        int start = str.indexOf(open);
        if (start != INDEX_NOT_FOUND) {
            int end = str.indexOf(close, start + open.length());
            if (end != INDEX_NOT_FOUND) {
                return str.substring(start + open.length(), end);
            }
        }
        return null;
    }
}

Related Tutorials