lak*_*doo 1 c# arrays string foreach
我有一个方法,删除字符串上的描述字,但我相信有更有效的方法来做到这一点.
该iMonster可以像脂肪兽人盗贼,和我想删除的脂肪.
private static string[] _adjectives = { "angry",
"big",
"fat",
"happy",
"large",
"nasty",
"fierce",
"thin",
"small",
"tall",
"short" };
private static string RemoveMonsterAdjective(string iMonster)
{
foreach (string adjective in _adjectives)
{
if (iMonster.Contains(adjective))
{
iMonster = iMonster.Replace(adjective, "").Trim();
break;
}
}
return iMonster;
}
Run Code Online (Sandbox Code Playgroud)
希望有人可以帮助我.提前致谢.
您可以使用正则表达式在一次调用中完成所有替换,如下所示:
return Regex.Replace(
iMonster,
@"\b(angry|big|fat|happy|...)\b",
""
).Trim();
Run Code Online (Sandbox Code Playgroud)
这种方法背后的想法是构造一个正则表达式,将任何形容词匹配为单个单词(因此"bigot"不匹配,而"big"匹配),并用空字符串替换该单词.