Split a String to a String[] so that each element is maximum 100 characters and ends in a space

前端 未结 4 991
囚心锁ツ
囚心锁ツ 2021-01-28 16:53

How do i do this? I tried something like this but I do not seem to be able to get any further.

public void speak(String text)
{
    String[] textArray = text.spl         


        
4条回答
  •  执笔经年
    2021-01-28 17:03

    I know this answer is late and a bit inefficient but I think it does the job nicely.

    public class StringSplitter
    { 
      private int maxCharactersPerLine = 100;
    
      public List GetTextLines(string text)
      { 
        var result = new List();
    
        if(text.Length <= this.maxCharactersPerLine)
        {
          result.Add(text);
          return result;
        }
    
        string words[] = text.Split(new[]{' '}, StringSplittingOptions.RemoveEmptyEntries);
    
        //accumolator, describes a line of text up to maximum character length.
        string temp = string.Empty; 
    
        //this is so that we don't append an empty space on each new line.
        bool isBeginingWord = true;
    
        foreach(var word in words)
        {
          //there is a possibility that a text line has more than maximum
          //consecutive characters without having a space. This is edge case. 
          if(temp.Length > this.maxCharactersPerLine)
          {
            result.Add(temp);
            continue;
          }
    
          //if adding the next word in the list will exceed the 
          //maximum characters per line of text
          if((temp + " " + word).Length > this.maxCharactersPerLine)
          {
            result.Add(temp);      //add the accumolator to the list.
            temp = "";             //reset the accumolator
            isBeginingWord= true;  //reset beginning of word flag.
            continue;
          }
    
          //adding the next word from the list results in accumolator still
          //still shorter than the maximum characters per line of text.
          if(isBeginingWord)
          {
            temp = word;
            isBeginingWord = false;
            continue;
          }
    
          temp = temp + " " + word;
        }
    
        return result;
      }
    }
    

提交回复
热议问题