32 から 175 までの Ascii 範囲にない文字列から文字を削除する必要があります。それ以外はすべて削除する必要があります。
.replace() や .remove() のようなものを使用して各無効な文字などを使用する代わりに、RegExp が最適なソリューションになるかどうかはよくわかりません。
どんな助けでも大歓迎です。
使用できます
Regex.Replace(myString, @"[^\x20-\xaf]+", "");
ここでの正規表現は、U+0020 から U+00AF (16 進表記で表現された 32–175) の範囲内 (クラスの開始時)[...]
以外のすべての文字で構成される文字クラス ( ) で構成されます。^
正規表現に関する限り、これはかなり基本的なものですが、あまり慣れていない人は困惑するかもしれません。
ただし、別のルートに進むこともできます。
new string(myString.Where(c => (c >= 32) && (c <= 175)).ToArray());
これはおそらく、何を読むのがより快適であるかに大きく依存します。正規表現の経験があまりないので、2番目の方がより明確になると思います。
いくつかのパフォーマンス測定値、それぞれ 10000 ラウンド、秒単位:
2000 characters, the first 143 of which are between 32 and 175
Regex without + 4.1171
Regex with + 0.4091
LINQ, where, new string 0.2176
LINQ, where, string.Join 0.2448
StringBuilder (xanatos) 0.0355
LINQ, horrible (HatSoft) 0.4917
2000 characters, all of which are between 32 and 175
Regex without + 0.4076
Regex with + 0.4099
LINQ, where, new string 0.3419
LINQ, where, string.Join 0.7412
StringBuilder (xanatos) 0.0740
LINQ, horrible (HatSoft) 0.4801
そうです、私のアプローチは最も遅いです:-)。あなたはおそらくxanatosの答えに行き、それを素敵で明確な名前のメソッドにラップするべきです。インラインでの使用、簡単な処理、またはパフォーマンスが問題にならない場合は、おそらく正規表現を使用します。
正規表現の書き方がわからない場合は、特に単純なものには使用しないでください。
var sb = new StringBuilder();
foreach (var c in str)
{
if (c >= 32 && c <= 175)
{
sb.Append(c);
}
}
var str2 = str.ToString();
正規表現を使用[^\x20-\xAF]+
し、空の文字列に置き換えます""
Regex.Replace(str, @"[^\x20-\xAF]+", "");
このようにlinqを使用するのはどうですか
string text = (from c in "AAA hello aaaa #### Y world"
let i = (int) c where i < 32 && i > 175 select c)
.Aggregate("", (current, c) => current + c);
static unsafe string TrimRange(string str, char from, char to)
{
int count = 0;
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
if ((ch >= from) && (ch <= to))
{
count++;
}
}
if (count == 0)
return String.Empty;
if (count == str.Length)
return str;
char * result = stackalloc char[count];
count = 0;
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
if ((ch >= from) && (ch <= to))
{
result[count ++] = ch;
}
}
return new String(result, 0, count);
}