Truncate string on whole words in .NET C#

前端 未结 10 1338
走了就别回头了
走了就别回头了 2020-11-29 22:43

I am trying to truncate some long text in C#, but I don\'t want my string to be cut off part way through a word. Does anyone have a function that I can use to truncate my st

10条回答
  •  一整个雨季
    2020-11-29 23:23

    Taking into account more than just a blank space separator (e.g. words can be separated by periods followed by newlines, followed by tabs, etc.), and several other edge cases, here is an appropriate extension method:

        public static string GetMaxWords(this string input, int maxWords, string truncateWith = "...", string additionalSeparators = ",-_:")
        {
            int words = 1;
            bool IsSeparator(char c) => Char.IsSeparator(c) || additionalSeparators.Contains(c);
    
            IEnumerable IterateChars()
            {
                yield return input[0];
    
                for (int i = 1; i < input.Length; i++)
                {
                    if (IsSeparator(input[i]) && !IsSeparator(input[i - 1]))
                        if (words == maxWords)
                        {
                            foreach (char c in truncateWith)
                                yield return c;
    
                            break;
                        }
                        else
                            words++;
    
                    yield return input[i];
                }
            }
    
            return !input.IsNullOrEmpty()
                ? new String(IterateChars().ToArray())
                : String.Empty;
        }
    

提交回复
热议问题