【问题标题】:Add newline between characters in every line in list of strings c#在字符串列表中的每一行的字符之间添加换行符c#
【发布时间】:2013-10-14 13:55:47
【问题描述】:

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

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

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

例如

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

【问题讨论】:

标签: c# string list


【解决方案1】:
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)));

【讨论】:

  • 谢谢伙计。 x=>... 是如何工作的?不管怎样,它解决了我的问题
  • 另外,如何将其存储在新列表中而不是将其写入文件?先生非常感谢您!编辑:想通了,附加ToList()
【解决方案2】:

使用您的集合,您可以做出一些不错的假设并打印子字符串。考虑以下示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2016-04-02
    • 2020-12-21
    • 1970-01-01
    • 2010-09-18
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多