Java String Chop Left chopFromLeft(String text, char character, int count)

Here you can find the source of chopFromLeft(String text, char character, int count)

Description

Chop the string off past the last stated occurrence of character

License

Apache License

Parameter

Parameter Description
text a parameter
character a parameter
count a parameter

Return

Chopped string.

Declaration

public static String chopFromLeft(String text, char character, int count) 

Method Source Code

//package com.java2s;
/*//from   w w w. j av  a  2s  .  c o m
 * 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.
 * 
 */

public class Main {
    /**
     * 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

  1. chopLeft(String str, char delimiter)
  2. ChopLf(String this_string, String chomp_off)