Get substring Before Last separator - Java java.lang

Java examples for java.lang:String Substring

Description

Get substring Before Last separator

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        String separator = "o";
        System.out.println(substringBeforeLast(str, separator));
    }/* www.j  a va2 s . com*/

    public static String substringBeforeLast(String str, String separator) {
        if (str == null || separator == null || str.length() == 0
                || separator.length() == 0) {
            return str;
        }
        int pos = str.lastIndexOf(separator);
        if (pos == -1) {
            return str;
        }
        return str.substring(0, pos);
    }
}

Related Tutorials