-2

我有一个包含任意行数的字符串列表。每行有 12 个字符长,我想将其内容打印到文本文件中。这很容易做到

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

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

例如

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
4

2 回答 2

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)));
于 2013-10-14T14:07:36.537 回答
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
于 2013-10-14T14:03:40.190 回答