Get substring Before separator - Java java.lang

Java examples for java.lang:String Substring

Description

Get substring Before separator

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sourceStr = "java2s.com";
        String expr = ".com";
        System.out.println(substringBefore(sourceStr, expr));
    }// w  w  w  .j a v  a2 s.c  om

    public static String substringBefore(String sourceStr, String expr) {
        if (isEmpty(sourceStr) || expr == null) {
            return sourceStr;
        }
        if (expr.length() == 0) {
            return sourceStr;
        }
        int pos = sourceStr.indexOf(expr);
        if (pos == -1) {
            return sourceStr;
        }
        return sourceStr.substring(0, pos);
    }

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

Related Tutorials