2013-10-14 71 views
-2

我有一个包含行任意数量的字符串列表。每行的长度为12个字符,我想将其内容打印到文本文件中。这是很容易做的在字符串列表字符之间添加新行中的每一行C#

System.IO.File.WriteAllLines(@".\strings.txt", myList); 

现在,我想每6个字符后插入newLine,有效地加倍列表的计数。

E.g

System.IO.File.WriteAllLines(@".\strings.txt", myList); 
// Output from strings.txt 
123456789ABC 
123456789ABC 
// ... 

// command to insert newLine after every 6 characters in myList 
System.IO.File.WriteAllLines(@".\strings.txt", myListWithNewLines); 
// Output from strings.txt 
123456 
789ABC 
123456 
789ABC 
+1

您可能会感兴趣在['String.Insert(int startIndex,string value)'中](http://msdn.microsoft.com/en-us/library/system.string.insert.aspx) – newfurniturey

+1

请downvoters,添加downvote的原因,我会尝试改进我的问题。 – chwi

回答

2
System.IO.File.WriteAllLines(@".\strings.txt", myList.Select(x => x.Length > 6 ? x.Insert(6, Environment.NewLine) : x)); 

或者,如果你知道每一行真的有12个字符:

System.IO.File.WriteAllLines(@".\strings.txt", myList.Select(x => x.Insert(6, Environment.NewLine))); 
+0

谢谢你。 'x => ...'如何工作?无论哪种方式,它解决了我的问题 – chwi

+0

另外,如何将它存储在一个新的列表中,而不是将其写入文件?先生非常感谢您!编辑:想通了,附加'ToList()' – chwi

0

使用自己设置的,你可以做一些很好的假设和打印字符串。请看下面的例子:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace StringSplit 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string input = @"123456789ABC 
123456789ABC"; 

      string[] lines = input.Split(new char[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries); 
      foreach (var l in lines) 
      { 
       System.Diagnostics.Debug.WriteLine(l.Substring(0, 6)); 
       System.Diagnostics.Debug.WriteLine(l.Substring(6, 6)); 
      } 
     } 
    } 
} 

输出:

123456 
789ABC 
123456 
789ABC 
相关问题