Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active July 25, 2020 18:30
Show Gist options
  • Save fabiolimace/b5e9acd8c1e9020f299cf48118bc35fb to your computer and use it in GitHub Desktop.
Save fabiolimace/b5e9acd8c1e9020f299cf48118bc35fb to your computer and use it in GitHub Desktop.
Remove chars from a String in Java
package your.package.name;
/**
* Utility class that removes chars from a String.
*
* @author: Fabio Lima 2020
*/
public class RemoveChars {
public static String remove(String string, String remove) {
return new String(remove(string.toCharArray(), remove.toCharArray()));
}
public static char[] remove(final char[] chars, char[] remove) {
int count = 0;
char[] buffer = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
boolean include = true;
for (int j = 0; j < remove.length; j++) {
if ((chars[i] == remove[j])) {
include = false;
break;
}
}
if (include) {
buffer[count++] = chars[i];
}
}
char[] output = new char[count];
System.arraycopy(buffer, 0, output, 0, count);
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String remove = "AEIOU";
System.out.println();
System.out.println("Remove AEIOU: " + string);
System.out.println("Result: " + RemoveChars.remove(string, remove));
}
}
/**
* OUTPUT
*
* Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
*
* Result: TH QCK BRWN FX JMPS VR TH LZY DG
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment