Returns the part of 'tail' that is not present at the end of 'text'. - Java java.lang

Java examples for java.lang:String End

Introduction

The following code shows how to Returns the part of 'tail' that is not present at the end of 'text'.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String text = "java2s.com";
        String tail = "om";
        System.out.println(getMissingTail(text, tail));
    }/*  w w w  .  j  av a  2 s.  c  o m*/

    /**
     * Returns the part of 'tail' that is not present at the end of 'text'. For
     * example if text = 'abc' and tail = 'cd' this method returns 'd'. If 'tail' can
     * not be found at the end of 'text', 'tail' is returned as is.
     */
    public static String getMissingTail(String text, String tail) {
        for (int i = 1; i < tail.length(); i++) {
            int endIndex = text.length();
            int end = Math.max(0, endIndex);
            int start = Math.max(0, end - i);
            String contentTail = text.substring(start, end);
            String proposalHead = tail.substring(0, i);
            if (contentTail.equals(proposalHead)) {
                return tail.substring(i);
            }
        }
        return tail;
    }
}

Related Tutorials