Strip a set of characters from a string: Difference between revisions
Strip a set of characters from a string (view source)
Revision as of 02:50, 13 May 2023
, 1 year ago→{{header|Java}}
m (→{{header|D}}) |
|||
Line 1,599:
=={{header|Java}}==
The most basic approach is to use the ''String.replace'' method.
<syntaxhighlight lang="java">
public static String stripChars(String inString, String toStrip) {▼
String stripCharacters(String string, String characters) {
for (char character : characters.toCharArray())
string = string.replace(String.valueOf(character), "");
return string;
}
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();
}
</syntaxhighlight>
You could use the ''String.replaceAll'' method, which takes a regular expression as it's first argument.
<syntaxhighlight lang="java">
/* be sure to 'quote' the 'characters' to avoid pattern collision */
characters = Pattern.quote(characters);
string = string.replaceAll("[%s]".formatted(characters), "");
▲}</syntaxhighlight>
return string;
}
</syntaxhighlight>
These will all produce the following string.
stripped: Sh ws soul strppr. Sh took my hrt!</pre>▼
<pre>
</pre>
=={{header|JavaScript}}==
|