Here you can find the source of chopFromRight(String text, char character, int count)
Parameter | Description |
---|---|
text | a parameter |
character | a parameter |
count | a parameter |
public static String chopFromRight(String text, char character, int count)
//package com.java2s; /*//from w w w . j ava2 s . 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 up to the last occurrence of character. * * @param text * @param character * @param count * * @return Chopped string. */ public static String chopFromRight(String text, char character, int count) { String target = text; int inTotal = countOf(character, text); if (inTotal > count && count > 0) { int total = (inTotal - count) + 1; 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(indexFrom, text.length()); } 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; } }