Write a function that takes a string and predicate as input and trim all the characters that matches to given predicate.
Signature
public static String trimLeading(final String str, final Predicate<Character> predicate)
Find the below working application.
TrimLeadCharacterDemo.java
package com.sample.app.strings;
import java.util.function.Predicate;
public class TrimLeadCharacterDemo {
public static boolean isEmpty(CharSequence str) {
return str == null || str.length() == 0;
}
public static String trimLeading(final String str, final Predicate<Character> predicate) {
if (isEmpty(str)) {
return str;
}
int counter = 0;
while (counter < str.length()) {
if (predicate.test(str.charAt(counter))) {
counter++;
continue;
}
return str.substring(counter);
}
return str.substring(counter);
}
public static void main(String[] args) {
String str1 = trimLeading("abcd", character -> character == 'c');
String str2 = trimLeading("ccbd", character -> character == 'c');
String str3 = trimLeading("ccccc", character -> character == 'c');
System.out.println("str1 : " + str1);
System.out.println("str2 : " + str2);
System.out.println("str3 : " + str3);
str1.trim();
}
}
Output
str1 : abcd str2 : bd str3 :
Previous Next Home
No comments:
Post a Comment