How to split string preserving whole words?

前端 未结 10 2285
梦谈多话
梦谈多话 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 09:47

    At first I was thinking this might be a Regex kind of thing but here's my shot at it:

    List parts = new List();
    int partLength = 35;
    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 > partLength) 
        {
            parts.Add(tempString.ToString());
            tempString.Clear();        
        }
        tempString.Append(" " + piece); 
    }
    

提交回复
热议问题