Java Keep Only Characters Present in a String using Apache Commons Lang
Tags: CharSetUtils Apache Commons Apache Commons Lang String
In this Java tutorial we learn how to populate a String which keeps only given characters present in the String using the CharSetUtils class of Apache Commons Lang library.
How to add Apache Commons Lang 3 library to your Java project
To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'org.apache.commons:commons-lang3:3.12.0'
To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/
How to keep characters present in a String in Java
The Apache Commons Lang library provides the method CharSetUtils.keep() to keep any of given characters present in a specified String. The following code example shows you how to use the CharSetUtils.keep() method.
KeepCharactersPresentInString.java
import org.apache.commons.lang3.CharSetUtils;
public class KeepCharactersPresentInString {
public static void main(String... args) {
String stringToTest = "Simple Solution, Java Tutorials";
String result1 = CharSetUtils.keep(stringToTest, "k-p");
String result2 = CharSetUtils.keep(stringToTest, "x-z");
String result3 = CharSetUtils.keep(stringToTest, "klmnop");
String result4 = CharSetUtils.keep(stringToTest, "xyz");
String result5 = CharSetUtils.keep(stringToTest, "k", "l", "m", "n", "o", "p");
String result6 = CharSetUtils.keep(stringToTest, "x", "y", "z");
System.out.println("Keep \"k-p\" result: " + result1);
System.out.println("Keep \"x-z\" result: " + result2);
System.out.println("Keep \"klmnop\" result: " + result3);
System.out.println("Keep \"xyz\" result: " + result4);
System.out.println("Keep \"k\", \"l\", \"m\", \"n\", \"o\", \"p\" result: " + result5);
System.out.println("Keep \"x\", \"y\", \"z\" result: " + result6);
}
}
Keep "k-p" result: mplolonol
Keep "x-z" result:
Keep "klmnop" result: mplolonol
Keep "xyz" result:
Keep "k", "l", "m", "n", "o", "p" result: mplolonol
Keep "x", "y", "z" result:
Happy Coding 😊