Java Delete Characters in a String using Apache Commons Lang
Tags: CharSetUtils Apache Commons Apache Commons Lang String
In this Java tutorial we learn how to delete any of the characters present in a given String using 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 delete Characters in a String in Java
The Apache Commons Lang library provides the method CharSetUtils.delete() to delete any of given characters that presents a specified String value. You can learn how to use the CharSetUtils.delete() method via example code below.
DeleteCharactersPresentInString.java
import org.apache.commons.lang3.CharSetUtils;
public class DeleteCharactersPresentInString {
public static void main(String... args) {
String stringToDelete = "Simple Solution, Java Tutorials";
String result1 = CharSetUtils.delete(stringToDelete, "k-n");
String result2 = CharSetUtils.delete(stringToDelete, "x-z");
String result3 = CharSetUtils.delete(stringToDelete, "klmn");
String result4 = CharSetUtils.delete(stringToDelete, "xyz");
String result5 = CharSetUtils.delete(stringToDelete, "k", "l", "m", "n");
String result6 = CharSetUtils.delete(stringToDelete, "x", "y", "z");
System.out.println("Delete \"k-n\" result: " + result1);
System.out.println("Delete \"x-z\" result: " + result2);
System.out.println("Delete \"klmn\" result: " + result3);
System.out.println("Delete \"xyz\" result: " + result4);
System.out.println("Delete \"k\", \"l\", \"m\", \"n\" result: " + result5);
System.out.println("Delete \"x\", \"y\", \"z\" result: " + result6);
}
}
Delete "k-n" result: Sipe Soutio, Java Tutorias
Delete "x-z" result: Simple Solution, Java Tutorials
Delete "klmn" result: Sipe Soutio, Java Tutorias
Delete "xyz" result: Simple Solution, Java Tutorials
Delete "k", "l", "m", "n" result: Sipe Soutio, Java Tutorias
Delete "x", "y", "z" result: Simple Solution, Java Tutorials
Happy Coding 😊