5

我需要创建一个TextWriter来填充一些数据。我将其StringWriter用作 TextWriter 并且业务逻辑工作正常。

我有一个无法更改的技术要求,因为它可能会破坏所有客户。string[]我需要从TextWriter由行分隔的字符串数组。

我试过这个但没有奏效:

using System;
using System.IO;
using System.Text;

namespace TextWriterToArrayOfStringsDemo
{
    internal static class Program
    {
        private static void Main()
        {
            var stringBuilder = new StringBuilder();
            using (TextWriter writer = new StringWriter(stringBuilder))
            {
                writer.Write("A");
                writer.WriteLine();
                writer.Write("B");
            }

            string fullString = stringBuilder.ToString();
            string replaced = fullString.Replace('\n', '\r');
            string[] arrayOfString = replaced.Split('\r');

            // Returns false but should return true
            Console.WriteLine(arrayOfString.Length == 2);
        }
    }
}

有什么想法或建议吗?

4

2 回答 2

7

尝试使用Environment.NewLine拆分而不是'\n'

        var stringBuilder = new StringBuilder();
        using (TextWriter writer = new StringWriter(stringBuilder))
        {
            writer.Write("A");
            writer.WriteLine();
            writer.Write("B");
        }

        string fullString = stringBuilder.ToString();
        string[] newline = new string[] { Environment.NewLine };
        string[] arrayOfString = fullString.Split(newline, StringSplitOptions.RemoveEmptyEntries);

        // Returns false but should return true
        Console.WriteLine(arrayOfString.Length == 2);
于 2012-04-24T18:00:41.320 回答
3

一个快速的解决方法是使用正则表达式拆分:

string[] arrayOfString = 
   System.Text.RegularExpressions.Regex.Split(stringBuilder.ToString(), "\r?\n")
于 2012-04-24T18:02:12.793 回答