2011-10-14 79 views
6

假設我有一個字符串與文本:「這是一個測試」。我如何將它分成n個字符?因此,如果n爲10,那麼它將顯示:C#換行符每n個字符

"THIS IS A " 
"TEST" 

..你明白了。原因是因爲我想把一條很大的一行分成更小的一行,就像換行。我想我可以使用string.Split(),但我不知道如何和我很困惑。

任何幫助,將不勝感激。

+1

可能重複[C#將一個字符串分解成相等的塊的每個大小4](HTTP:/ /stackoverflow.com/questions/1450774/c-sharp-split-a-string-into-equal-chunks-each-of-size-4) –

回答

16

讓我們借用my answer在代碼審查的實現。這將插入線每ň字符突破:

public static string SpliceText(string text, int lineLength) { 
    return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine); 
} 

編輯:
要返回一個字符串數組來代替:

public static string[] SpliceText(string text, int lineLength) { 
    return Regex.Matches(text, ".{1," + lineLength + "}").Cast<Match>().Select(m => m.Value).ToArray(); 
} 
2

你應該可以使用這個正則表達式。這裏有一個例子:

//in this case n = 10 - adjust as needed 
List<string> groups = (from Match m in Regex.Matches(str, ".{1,10}") 
         select m.Value).ToList(); 

string newString = String.Join(Environment.NewLine, lst.ToArray()); 

請參考此問題的詳細信息:
Splitting a string into chunks of a certain size

1

可能不是最優化的方式,但沒有正則表達式:

string test = "my awesome line of text which will be split every n characters"; 
int nInterval = 10; 
string res = String.Concat(test.Select((c, i) => i > 0 && (i % nInterval) == 0 ? c.ToString() + Environment.NewLine : c.ToString())); 
+0

最好使用'String.Concat()'來代替連接一個空的字符串。 –

+0

感謝您的提示! – Peter

3

也許這可以用來有效處理極端大的文件:

public IEnumerable<string> GetChunks(this string sourceString, int chunkLength) 
{ 
    using(var sr = new StringReader(sourceString)) 
    { 
     var buffer = new char[chunkLength]; 
     int read; 
     while((read= sr.Read(buffer, 0, chunkLength)) == chunkLength) 
     { 
      yield return new string(buffer, 0, read); 
     }   
    } 
} 

其實,這適用於任何TextReaderStreamReader是最常用的TextReader。您可以處理非常大的文本文件(IIS日誌文件,SharePoint日誌文件等),而無需加載整個文件,但可以逐行閱讀。

1

說回這個做代碼審查後,有做同樣的另一種方式,而無需使用的Regex

public static IEnumerable<string> SplitText(string text, int length) 
{ 
    for (int i = 0; i < text.Length; i += length) 
    { 
     yield return text.Substring(i, Math.Min(length, text.Length - i)); 
    } 
} 
相關問題