Splits text at the last occurrence of separator and returns the right part, excluding the separator. - Java java.lang

Java examples for java.lang:String Split

Description

Splits text at the last occurrence of separator and returns the right part, excluding the separator.

Demo Code


//package com.java2s;

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

    /**
     * Splits <code>text</code> at the last occurrence of <code>separator</code>
     * and returns the right part, excluding the separator. 
     *
     * @param text the haystack
     * @param separator the needle
     * @return text, if no occurrence can be found; the empty string, if the last character is a seperator
     */
    public static String lastToken(String text, String separator) {
        if (separator == null) {
            throw new IllegalArgumentException("separator must not be null");
        }
        if (separator.length() == 0) {
            throw new IllegalArgumentException(
                    "separator must not be empty");
        }

        int i = text.lastIndexOf(separator);
        if (i == -1) {
            return text;
        } else if (i == text.length() - 1) {
            return "";
        } else {
            return text.substring(i + separator.length(), text.length());
        }
    }
}

Related Tutorials