Strip a set of characters from a string: Difference between revisions

Line 1,599:
 
=={{header|Java}}==
The most basic approach is to use the ''String.replace'' method.
<syntaxhighlight lang="java">class StripChars {
public static String stripChars(String inString, String toStrip) {
String stripCharacters(String string, String characters) {
return inString.replaceAll("[" + toStrip + "]", "");
for (char character : characters.toCharArray())
string = string.replace(String.valueOf(character), "");
return string;
}
}</syntaxhighlight>
You could also use a ''StringBuilder'' which provides a ''deleteCharAt'' method.
<syntaxhighlight lang="java">
String stripCharacters(String string, String characters) {
StringBuilder stripped = new StringBuilder(string);
/* traversing the string backwards is necessary to avoid collision */
for (int index = string.length() - 1; index >= 0; index--) {
if (characters.contains(String.valueOf(string.charAt(index))))
stripped.deleteCharAt(index);
}
return stripped.toString();
 
}
public static void main(String[] args) {
</syntaxhighlight>
String sentence = "She was a soul stripper. She took my heart!";
You could use the ''String.replaceAll'' method, which takes a regular expression as it's first argument.
String chars = "aei";
<syntaxhighlight lang="java">
System.out.println("sentence: " + sentence);
public static String stripCharsstripCharacters(String inStringstring, String toStripcharacters) {
System.out.println("to strip: " + chars);
/* be sure to 'quote' the 'characters' to avoid pattern collision */
System.out.println("stripped: " + stripChars(sentence, chars));
characters = Pattern.quote(characters);
}
string = string.replaceAll("[%s]".formatted(characters), "");
}</syntaxhighlight>
return string;
{{out}}
}
<pre>sentence: She was a soul stripper. She took my heart!
</syntaxhighlight>
to strip: aei
These will all produce the following string.
stripped: Sh ws soul strppr. Sh took my hrt!</pre>
<pre>
stripped: Sh ws soul strppr. Sh took my hrt!</pre>
</pre>
 
=={{header|JavaScript}}==
118

edits