C# 文字列から複数の指定した文字を削除する

C#で、文字列から複数の指定した文字を削除するサンプルコードを記述してます。削除したい文字を配列などで指定してから「Replace」で空文字に置換することで削除できます。
環境
- OS windows11 pro 64bit
- Microsoft Visual Studio Community 2022 Version 17.2.6
文字列から複数の指定した文字を削除
文字列から複数の指定した文字を削除するには、配列で削除する文字を用意して、ループ処理で「Replace」により「””」を使用して空文字に変換して削除します。
using System;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string str = "abcde-abcde-abcde";
// 削除する文字を指定
string[] charDelete = new string[] { "a", "b", "d" };
foreach (var c in charDelete)
{
str = str.Replace(c, "");
}
Console.WriteLine(str); // ce-ce-ce
}
}
}
実行結果

正規表現
「Regex」を使用して、正規表現を使用する方法もあります。
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string str = "abcde-abcde-abcde";
// 削除する文字を指定して削除
str = Regex.Replace(str, "[a,b.d]", "");
Console.WriteLine(str);
}
}
}
-
前の記事
Flutter エラー「Evaluation of this constant expression throws an exception.dart(const_eval_throws_exception)」が発生した場合の対処法 2022.11.21
-
次の記事
CentOS9 プログラミング言語「gravity」をインストールして実行する 2022.11.21
コメントを書く