1

我有一种方法可以根据字符串删除描述词,但我相信有更有效的方法可以做到这一点。

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;
    }

希望有人可以帮助我。提前致谢。

4

2 回答 2

5

您可以使用正则表达式在一次调用中完成所有替换,如下所示:

return Regex.Replace(
    iMonster,
    @"\b(angry|big|fat|happy|...)\b",
    ""
).Trim();

这种方法背后的想法是构造一个正则表达式,将任何形容词匹配为单个单词(因此“bigot”将不匹配,而“big”将匹配),并将该单词替换为空字符串。

这是关于 ideone 的演示

于 2013-01-05T17:46:13.500 回答
4

另一个可能的简短解决方案是:

var words = iMonster.Split(' ');
return string.Join(" ", words.Except(_adjectives));

我做了一些分析并比较了各种解决方案。

输入fat angry orc happy rogue和 1000000 次迭代:

00:00:01.8457067 lakedoo
00:00:01.9772477 Eve
00:00:04.3859120 dasblinkenlight

需要提到的是,我改编了 dasblinkenlight 的解决方案,以便在正则表达式中包含所有形容词。

编辑:通过删除中断更正了lakedoo的方法。

于 2013-01-05T18:00:56.543 回答