2011-10-14 16 views
6

"THIS IS A TEST"という文字列があるとします。どのようにn文字ごとに分割するのですか?したがって、nが10の場合は、次のように表示されます。C#はn文字ごとに改行します

"THIS IS A " 
"TEST" 

..あなたはアイデアを得ます。理由は、非常に大きな行を小さな行に分割したい、ワードラップのようなものだからです。私はstring.Split()を使用することができると思うが、これについてはわからないが、私は混乱している。

ご協力いただければ幸いです。

+1

が重複する可能性を使用せずに同じことを行うための別の方法があります/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.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

ない最も最適な方法を、しかし、正規表現なし:

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

編集:これは、行がすべてのn個文字を破る挿入

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); 
     }   
    } 
} 

実際には、これはTextReaderに適用されます。 StreamReaderが最も一般的に使用されますTextReader。非常に大きなテキストファイル(IISログファイル、SharePointログファイルなど)は、ファイル全体を読み込む必要はなく、行単位で読み込むことができます。 /:コードレビューを行った後に戻ってこれに来

1

は、[等しいチャンクに文字列サイズ4の各C#スプリット](HTTPの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)); 
    } 
}