Truncate string on whole words in .NET C#

前端 未结 10 1371
走了就别回头了
走了就别回头了 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:18

    Heres what i came up with. This is to get the rest of the sentence also in chunks.

    public static List SplitTheSentenceAtWord(this string originalString, int length)
        {
            try
            {
                List truncatedStrings = new List();
                if (originalString == null || originalString.Trim().Length <= length)
                {
                    truncatedStrings.Add(originalString);
                    return truncatedStrings;
                }
                int index = originalString.Trim().LastIndexOf(" ");
    
                while ((index + 3) > length)
                    index = originalString.Substring(0, index).Trim().LastIndexOf(" ");
    
                if (index > 0)
                {
                    string retValue = originalString.Substring(0, index) + "...";
                    truncatedStrings.Add(retValue);
    
                    string shortWord2 = originalString;
                    if (retValue.EndsWith("..."))
                    {
                        shortWord2 = retValue.Replace("...", "");
                    }
                    shortWord2 = originalString.Substring(shortWord2.Length);
    
                    if (shortWord2.Length > length) //truncate it further
                    {
                        List retValues = SplitTheSentenceAtWord(shortWord2.TrimStart(), length);
                        truncatedStrings.AddRange(retValues);
                    }
                    else
                    {
                        truncatedStrings.Add(shortWord2.TrimStart());
                    }
                    return truncatedStrings;
                }
                var retVal_Last = originalString.Substring(0, length - 3);
                truncatedStrings.Add(retVal_Last + "...");
                if (originalString.Length > length)//truncate it further
                {
                    string shortWord3 = originalString;
                    if (originalString.EndsWith("..."))
                    {
                        shortWord3 = originalString.Replace("...", "");
                    }
                    shortWord3 = originalString.Substring(retVal_Last.Length);
                    List retValues = SplitTheSentenceAtWord(shortWord3.TrimStart(), length);
    
                    truncatedStrings.AddRange(retValues);
                }
                else
                {
                    truncatedStrings.Add(retVal_Last + "...");
                }
                return truncatedStrings;
            }
            catch
            {
                return new List { originalString };
            }
        }
    

提交回复
热议问题