var stringWithLongWords = "Here's a text with tooooooooooooo long words";
我想把这个东西通过过滤器。
var trimmed = TrimLongWords(stringWithLongWords, 6);
为了获得一个输出,其中每个单词只能包含最多6个字符:
"Here's a text with tooooo long words"
任何好的性能实现想法?.NET 中是否有自动处理此操作的工具?
我目前正在使用以下代码:
private static string TrimLongWords(string original, int maxCount)
{
return string.Join(" ", original.Split(' ').Select(x => x.Substring(0, x.Length > maxCount ? maxCount : x.Length)));
}
理论上这种方法可行,但是如果长单词以空格以外的分隔符结尾,则会输出错误。例如:
最终会变成这样:This is sweeeeeeeeeeeeeeeet! And something more.
更新:This is sweeeeeeee And something more.
好吧,评论太好了,我意识到这可能有太多“如果”。也许忘记分隔符会更好。如果一个单词被修剪,可以用三个点来表示。以下是一些将单词修剪为最大5个字符的示例:
Apocalypse now! -> Apoca... now!
Apocalypse! -> Apoca...
!Example! -> !Exam...
This is sweeeeeeeeeeeeeeeet! And something more. - > This is sweee... And somet... more.
Antidisestablishmentarianism
,您想要的输出仅为Antidi
?你脑子里怎么会想到这么奇怪的想法? - http://imgc.allpostersimages.com/images/P-473-488-90/60/6067/4NZD100Z/posters/sam-gross-it-sort-of-makes-you-stop-and-think-doesn-t-it-new-yorker-cartoon.jpg :) - balexandrePseudo
吗? - devnull!Example!
、Example!!!
、Exa?!mple
这样的字符串,应该发生什么情况? - Chris