2017-02-23 84 views
-2

嗨,我有一個字符串段,包含25個字和300個字符,我想將它設置爲可以包含40個字符的標籤集。我正在嘗試下面的代碼與字符長度。將字符串拆分成長度可變的較小字c#

public static List<string> _mSplitByLength(this string str, int maxLength) 
{ 
    List<string> _a = new List<string>(); 
    for (int index = 0; index < str.Length; index += maxLength) 
    { 
     _a.Add(str.Substring(index, Math.Min(maxLength, str.Length - index))); 
    } 
    return _a; 
} 

與上面的代碼我可以將字符串拆分爲40個字符,但問題是它也拆分字。

想我的字符串是"My school Name is stack over flow High school."這是46個字符所以我的代碼它越來越喜歡這個

list 1 = "My school Name is stack over flow High s" 
list 2 = "chool." 

我的問題是如何在詞的基礎上拆分字符串。如果最後一個詞沒有提交,那麼它應該轉移到下一個列表。

我的目標是

list 1 = "My school Name is stack over flow High " 
list 2 = "school." 

回答

2

試試這個:

string text = "My school Name is stack over flow High school."; 
List<string> lines = 
    text 
     .Split(' ') 
     .Aggregate(new [] { "" }.ToList(), (a, x) => 
     { 
      var last = a[a.Count - 1]; 
      if ((last + " " + x).Length > 40) 
      { 
       a.Add(x); 
      } 
      else 
      { 
       a[a.Count - 1] = (last + " " + x).Trim(); 
      } 
      return a; 
     }); 

我得到了這一點:

 
My school Name is stack over flow High 
school. 
相關問題