我的要求是:
我必须替换一些特殊字符,如*'",_^ @ 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)
小智 10
Regex.Replace(source_string, @"[^\w\d]", "_");
Run Code Online (Sandbox Code Playgroud)
这会将给定字符串 ( ) 中的所有非字母和非数字替换为“_” source_string。
使用正则表达式
Regex.Replace("Hello*Hello'Hello&Hello@Hello Hello", @"[^0-9A-Za-z ,]", "").Replace(" ", "-")
Run Code Online (Sandbox Code Playgroud)
它将使用" - "替换string.Empty和Space中的所有特殊字符.
创建一组更改以进行迭代:
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)
您可以尝试使用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)