替换C#中的特殊字符串

Ven*_*kat 15 c#

我的要求是:

我必须替换一些特殊字符,如*'",_&#^ @ with string.Empty,我必须用空格替换空格-.

这是我的代码:

 Charseparated = Charseparated
    .Replace("*","")
    .Replace("'","")
    .Replace("&","")
    .Replace("@","") ...
Run Code Online (Sandbox Code Playgroud)

要替换这么多角色,我必须尽可能多地使用Replace我想要避免的角色.

是否有另一种有效的方法来删除特殊字符,但同时用-?替换空格?

Rah*_*hul 12

我相信,最好是使用正则表达式,如下所示

s/[*'",_&#^@]/ /g
Run Code Online (Sandbox Code Playgroud)

您可以使用Regex类来实现此目的

Regex reg = new Regex("[*'\",_&#^@]");
str1 = reg.Replace(str1, string.Empty);

Regex reg1 = new Regex("[ ]");
str1 = reg.Replace(str1, "-");
Run Code Online (Sandbox Code Playgroud)

  • @Venkat更正. (2认同)
  • 还要考虑静态Regex.Replace(输入,模式,替换).我更喜欢单次使用正则表达式 (2认同)

小智 10

Regex.Replace(source_string, @"[^\w\d]", "_");
Run Code Online (Sandbox Code Playgroud)

这会将给定字符串 ( ) 中的所有非字母和非数字替换为“_” source_string


Mit*_*iya 7

使用正则表达式

Regex.Replace("Hello*Hello'Hello&Hello@Hello Hello", @"[^0-9A-Za-z ,]", "").Replace(" ", "-")
Run Code Online (Sandbox Code Playgroud)

它将使用" - "替换string.Empty和Space中的所有特殊字符.


Pat*_*man 6

创建一组更改以进行迭代:

var replacements = new []
                   { new { Old = "*", New = string.Empty }
                   // all your other replacements, removed for brevity
                   , new { Old = " ", New = "-" }
                   }

foreach (var r in replacements)
{
    Charseparated = Charseparated.Replace(r.Old, r.New);
}
Run Code Online (Sandbox Code Playgroud)

  • 除非我们得到一个特定的用例,否则每个"性能测量"都没有意义.如果可能的输入大小平均低于20个字符,则对100k字符串执行测量无关紧要."避免过早优化"意味着在这种情况下:使代码工作和维护,并且只有在您有其他指示的测量时才进行优化. (3认同)

Dmi*_*nko 5

您可以尝试使用LINQ

  var source = "lala * lalala @ whowrotethis # ohcomeon &";

  var result = string.Concat(source.Select(c => c == ' ' 
     ? "-" 
     : "*'\",_&#^@".Contains(c) ? "" 
     : c.ToString()));
Run Code Online (Sandbox Code Playgroud)