回答:
var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "@", ",", ".", ";", "'" };
foreach (var c in charsToRemove)
{
str = str.Replace(c, string.Empty);
}
しかし、文字以外の文字をすべて削除したい場合は、別のアプローチを提案することがあります
var str = "My name @is ,Wan.;'; Wan";
str = new string((from c in str
where char.IsWhiteSpace(c) || char.IsLetterOrDigit(c)
select c
).ToArray());
RegEx-高速テキスト操作用に設計されたエンジン-の理想的なアプリケーションのように聞こえます。この場合:
Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)
あなたの質問にはあまり具体的ではありませんが、正規表現で受け入れ可能な文字をホワイトリストに登録することで、文字列(スペースを除く)からすべての句読点を削除することができます。
string dirty = "My name @is ,Wan.;'; Wan";
// only space, capital A-Z, lowercase a-z, and digits 0-9 are allowed in the string
string clean = Regex.Replace(dirty, "[^A-Za-z0-9 ]", "");
文からスペースを削除しないように、9の後にスペースがあることに注意してください。3番目の引数は空の文字列で、正規表現に属さない部分文字列を置き換える役割を果たします。
さまざまな提案の比較(および1文字の置換のコンテキストでのターゲットのさまざまなサイズと位置との比較)。
この特定のケースでは、ターゲットでの分割と置換(この場合は空の文字列)での結合は、少なくとも3倍の速度で最速です。最終的に、パフォーマンスは、置換が行われる置換の数によって異なります。ソース、およびソースのサイズ。#ymmv
(完全な結果はこちら)
| Test | Compare | Elapsed |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin | 1.00x | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per] |
| Replace | 2.77x | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per] |
| RegexCompiled | 5.27x | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit | 5.43x | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per] |
| Regex, Uncompiled | 5.85x | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex | 6.81x | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive | 7.52x | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |
(注:PerfおよびVsは、私が書いたタイミング拡張です)
void test(string title, string sample, string target, string replacement) {
var targets = target.ToCharArray();
var tox = "[" + target + "]";
var x = new Regex(tox);
var xc = new Regex(tox, RegexOptions.Compiled);
var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// no, don't dump the results
var p = new Perf/*<string>*/();
p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));
var trunc = 40;
var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;
p.Vs(header);
}
void Main()
{
// also see /programming/7411438/remove-characters-from-c-sharp-string
"Control".Perf(n => { var s = "*"; });
var text = "My name @is ,Wan.;'; Wan";
var clean = new[] { '@', ',', '.', ';', '\'' };
test("stackoverflow", text, string.Concat(clean), string.Empty);
var target = "o";
var f = "x";
var replacement = "1";
var fillers = new Dictionary<string, string> {
{ "short", new String(f[0], 10) },
{ "med", new String(f[0], 300) },
{ "long", new String(f[0], 1000) },
{ "huge", new String(f[0], 10000) }
};
var formats = new Dictionary<string, string> {
{ "start", "{0}{1}{1}" },
{ "middle", "{1}{0}{1}" },
{ "end", "{1}{1}{0}" }
};
foreach(var filler in fillers)
foreach(var format in formats) {
var title = string.Join("-", filler.Key, format.Key);
var sample = string.Format(format.Value, target, filler.Value);
test(title, sample, target, replacement);
}
}
string x = "My name @is ,Wan.;'; Wan";
string modifiedString = x.Replace("@", "").Replace(",", "").Replace(".", "").Replace(";", "").Replace("'", "");
最も簡単な方法は次のようにすることString.Replaceです:
String s = string.Replace("StringToReplace", "NewString");
別の簡単な解決策:
var forbiddenChars = @"@,.;'".ToCharArray();
var dirty = "My name @is ,Wan.;'; Wan";
var clean = new string(dirty.Where(c => !forbiddenChars.Contains(c)).ToArray());
new List<string> { "@", ",", ".", ";", "'" }.ForEach(m => str = str.Replace(m, ""));
文字列は単なる文字配列なので、Linqを使用して置換を行います(上記のAlbinと同様ですが、linq containsステートメントを使用して置換を行います)。
var resultString = new string(
(from ch in "My name @is ,Wan.;'; Wan"
where ! @"@,.;\'".Contains(ch)
select ch).ToArray());
最初の文字列は文字を置き換える文字列で、2番目の文字列は文字を含む単純な文字列です
これをここに捨てたほうがいい。
文字列から文字を削除する拡張機能を作成します。
public static string RemoveChars(this string input, params char[] chars)
{
var sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (!chars.Contains(input[i]))
sb.Append(input[i]);
}
return sb.ToString();
}
そしてそれはこのように使用できます:
string str = "My name @is ,Wan.;'; Wan";
string cleanedUpString = str.RemoveChars('@', ',', '.', ';', '\'');
またはこのように:
string str = "My name @is ,Wan.;'; Wan".RemoveChars('@', ',', '.', ';', '\'');
最短の方法は、LINQとstring.Concat:
var input = @"My name @is ,Wan.;'; Wan";
var chrs = new[] {'@', ',', '.', ';', '\''};
var result = string.Concat(input.Where(c => !chrs.Contains(c)));
// => result = "My name is Wan Wan"
C#デモを参照してください。注string.Concatへのショートカットですstring.Join("", ...)。
正規表現の方が遅いと考えられていますが、正規表現を使用して個々の既知の文字を削除することは、動的に構築することも可能です。ただし、これはそのような動的正規表現を構築する方法です(必要なのは文字クラスだけです)。
var pattern = $"[{Regex.Escape(new string(chrs))}]+";
var result = Regex.Replace(input, pattern, string.Empty);
別のC#デモを参照してください。正規表現は次のようになります[@,\.;']+(マッチングの一つ以上の(+)の連続発生@、,、.、;または'文字)のドットをエスケープする必要はありませんが、Regex.Escape他のエスケープしなければならない文字、のようなエスケープする必要があります\、^、]または-その位置を文字クラス内では予測できません。
これは、私が書いた方法で、少し異なるアプローチを取ります。削除する文字を指定するのではなく、保持する文字をメソッドに指示します。これにより、他のすべての文字が削除されます。
OPの例では、彼はアルファベット文字とスペースのみを保持したいと考えています。私のメソッドの呼び出しは次のようになります(C#デモ)。
var str = "My name @is ,Wan.;'; Wan";
// "My name is Wan Wan"
var result = RemoveExcept(str, alphas: true, spaces: true);
これが私の方法です:
/// <summary>
/// Returns a copy of the original string containing only the set of whitelisted characters.
/// </summary>
/// <param name="value">The string that will be copied and scrubbed.</param>
/// <param name="alphas">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="numerics">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="dashes">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="underlines">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="spaces">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="periods">If true, all decimal characters (".") will be preserved; otherwise, they will be removed.</param>
public static string RemoveExcept(string value, bool alphas = false, bool numerics = false, bool dashes = false, bool underlines = false, bool spaces = false, bool periods = false) {
if (string.IsNullOrWhiteSpace(value)) return value;
if (new[] { alphas, numerics, dashes, underlines, spaces, periods }.All(x => x == false)) return value;
var whitelistChars = new HashSet<char>(string.Concat(
alphas ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : "",
numerics ? "0123456789" : "",
dashes ? "-" : "",
underlines ? "_" : "",
periods ? "." : "",
spaces ? " " : ""
).ToCharArray());
var scrubbedValue = value.Aggregate(new StringBuilder(), (sb, @char) => {
if (whitelistChars.Contains(@char)) sb.Append(@char);
return sb;
}).ToString();
return scrubbedValue;
}
ここにたくさんの良い答えがあります。これは、正確性をテストするために使用できるいくつかの単体テストと一緒に追加したものです。私の解決策は上記の@Rianneのそれに似ていますが、ISetを使用して、置換文字にO(1)ルックアップ時間を提供します(また、 @Albin SunnanboのLinqソリューションに似ています)。
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Returns a string with the specified characters removed.
/// </summary>
/// <param name="source">The string to filter.</param>
/// <param name="removeCharacters">The characters to remove.</param>
/// <returns>A new <see cref="System.String"/> with the specified characters removed.</returns>
public static string Remove(this string source, IEnumerable<char> removeCharacters)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (removeCharacters == null)
{
throw new ArgumentNullException("removeCharacters");
}
// First see if we were given a collection that supports ISet
ISet<char> replaceChars = removeCharacters as ISet<char>;
if (replaceChars == null)
{
replaceChars = new HashSet<char>(removeCharacters);
}
IEnumerable<char> filtered = source.Where(currentChar => !replaceChars.Contains(currentChar));
return new string(filtered.ToArray());
}
NUnit(2.6+)テストはこちら
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class StringExtensionMethodsTests
{
[TestCaseSource(typeof(StringExtensionMethodsTests_Remove_Tests))]
public void Remove(string targetString, IEnumerable<char> removeCharacters, string expected)
{
string actual = StringExtensionMethods.Remove(targetString, removeCharacters);
Assert.That(actual, Is.EqualTo(expected));
}
[TestCaseSource(typeof(StringExtensionMethodsTests_Remove_ParameterValidation_Tests))]
public void Remove_ParameterValidation(string targetString, IEnumerable<char> removeCharacters)
{
Assert.Throws<ArgumentNullException>(() => StringExtensionMethods.Remove(targetString, removeCharacters));
}
}
internal class StringExtensionMethodsTests_Remove_Tests : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new TestCaseData("My name @is ,Wan.;'; Wan", new char[] { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingCharArray");
yield return new TestCaseData("My name @is ,Wan.;'; Wan", new HashSet<char> { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingISetCollection");
yield return new TestCaseData(string.Empty, new char[1], string.Empty).SetName("EmptyStringNoReplacementCharactersYieldsEmptyString");
yield return new TestCaseData(string.Empty, new char[] { 'A', 'B', 'C' }, string.Empty).SetName("EmptyStringReplacementCharsYieldsEmptyString");
yield return new TestCaseData("No replacement characters", new char[1], "No replacement characters").SetName("StringNoReplacementCharactersYieldsString");
yield return new TestCaseData("No characters will be replaced", new char[] { 'Z' }, "No characters will be replaced").SetName("StringNonExistantReplacementCharactersYieldsString");
yield return new TestCaseData("AaBbCc", new char[] { 'a', 'C' }, "ABbc").SetName("CaseSensitivityReplacements");
yield return new TestCaseData("ABC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemoved");
yield return new TestCaseData("AABBBBBBCC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemovedMultiple");
yield return new TestCaseData("Test That They Didn't Attempt To Use .Except() which returns distinct characters", new char[] { '(', ')' }, "Test That They Didn't Attempt To Use .Except which returns distinct characters").SetName("ValidateTheStringIsNotJustDistinctCharacters");
}
}
internal class StringExtensionMethodsTests_Remove_ParameterValidation_Tests : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new TestCaseData(null, null);
yield return new TestCaseData("valid string", null);
yield return new TestCaseData(null, new char[1]);
}
}
私が通常同じケースで使用するその強力な方法:
private string Normalize(string text)
{
return string.Join("",
from ch in text
where char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)
select ch);
}
楽しい...
オールドスクールインプレースコピー/ストンプ:
private static string RemoveDirtyCharsFromString(string in_string)
{
int index = 0;
int removed = 0;
byte[] in_array = Encoding.UTF8.GetBytes(in_string);
foreach (byte element in in_array)
{
if ((element == ' ') ||
(element == '-') ||
(element == ':'))
{
removed++;
}
else
{
in_array[index] = element;
index++;
}
}
Array.Resize<byte>(ref in_array, (in_array.Length - removed));
return(System.Text.Encoding.UTF8.GetString(in_array, 0, in_array.Length));
}
他のメソッドの効率(つまり、C#実行の副作用として発生するすべての関数呼び出しとインスタンス化のオーバーヘッド)がわからない。
私はそれを拡張メソッドにし、文字列配列を使用すると、charも文字列にすることができるため、string[]より便利だと思いchar[]ます。
public static class Helper
{
public static string RemoverStrs(this string str, string[] removeStrs)
{
foreach (var removeStr in removeStrs)
str = str.Replace(removeStr, "");
return str;
}
}
その後、どこでも使用できます。
string myname = "My name @is ,Wan.;'; Wan";
string result = myname.RemoveStrs(new[]{ "@", ",", ".", ";", "\\"});
@drzausからパフォーマンスの数値を取り入れて、最速のアルゴリズムを使用する拡張メソッドを次に示します。
public static class StringEx
{
public static string RemoveCharacters(this string s, params char[] unwantedCharacters)
=> s == null ? null : string.Join(string.Empty, s.Split(unwantedCharacters));
}
使用法
var name = "edward woodward!";
var removeDs = name.RemoveCharacters('d', '!');
Assert.Equal("ewar woowar", removeDs); // old joke