How to split string preserving whole words?

前端 未结 10 2298
梦谈多话
梦谈多话 2020-11-30 09:18

I need to split long sentence into parts preserving whole words. Each part should have given maximum number of characters (including space, dots etc.). For example:

10条回答
  •  旧时难觅i
    2020-11-30 10:00

    Joel there is a little bug in your code that I've corrected here:

    public static string[] StringSplitWrap(string sentence, int MaxLength)
    {
            List parts = new List();
            string sentence = "Silver badges are awarded for longer term goals. Silver badges are uncommon.";
    
            string[] pieces = sentence.Split(' ');
            StringBuilder tempString = new StringBuilder("");
    
            foreach (var piece in pieces)
            {
                if (piece.Length + tempString.Length + 1 > MaxLength)
                {
                    parts.Add(tempString.ToString());
                    tempString.Clear();
                }
                tempString.Append((tempString.Length == 0 ? "" : " ") + piece);
            }
    
            if (tempString.Length>0)
                parts.Add(tempString.ToString());
    
            return parts.ToArray();
    }
    

提交回复
热议问题