Cut the string to be <= 80 characters AND must keep the words without cutting them

前端 未结 4 1597
春和景丽
春和景丽 2021-01-24 07:22

I am new to C#, but I have a requirement to cut the strings to be <= 80 characters AND they must keep the words integrity (without cutting them)

Examples

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 07:50

    Here's an approach without using Regex: just split the string (however you'd like) into whatever you consider "words" to be. Then, just start concatenating them together using a StringBuilder, checking for your desired length, until you can't add the next "word". Then, just return the string that you have built up so far.

    (Untested code ahead)

    public string TruncateWithPreservation(string s, int len)
    {
        string[] parts = s.Split(' ');
        StringBuilder sb = new StringBuilder();
    
        foreach (string part in parts)
        {
            if (sb.Length + part.Length > len)
                break;
    
            sb.Append(' ');
            sb.Append(part);
        }
    
        return sb.ToString();
    }
    

提交回复
热议问题