Chop the string off past the last stated occurrence of character - Java java.lang

Java examples for java.lang:String Trim

Description

Chop the string off past the last stated occurrence of character

Demo Code

/*//from ww  w.j  a v  a2  s .c  om
 * Copyright 2011 - Alistair Rutherford - www.netthreads.co.uk
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String text = "java2s.com";
        char character = 'a';
        int count = 42;
        System.out.println(chopFromLeft(text, character, count));
    }

    /**
     * Chop the string off past the last stated occurrence of character
     * 
     * @param text
     * @param character
     * @param count
     * 
     * @return Chopped string.
     */
    public static String chopFromLeft(String text, char character, int count) {
        String target = text;
        int inTotal = countOf(character, text);

        if (inTotal > count && count > 0) {
            int total = count;
            int indexFrom = 0;
            int nextIndex = 0;
            while (total > 0) {
                nextIndex = text.indexOf(character, indexFrom);
                if (nextIndex > 0) {
                    total--;
                }
                // Skip past target character.
                indexFrom = nextIndex + 1;
            }

            target = text.substring(0, indexFrom - 1);
        }

        return target;
    }

    /**
     * Return the number of occurrences of target character in the supplied string.
     * 
     * @param character
     * @param text 
     * 
     * @return Occurrence count.
     */
    public static int countOf(char character, String text) {
        int count = 0;
        int indexFrom = 0;
        int nextIndex = 0;
        while (nextIndex >= 0) {
            nextIndex = text.indexOf(character, indexFrom);
            if (nextIndex > 0) {
                count++;
            }
            // Skip past target character.
            indexFrom = nextIndex + 1;
        }

        return count;
    }
}

Related Tutorials