2

我有这样的文字

 5     1     5     1     5      1     5      1       
       1

我必须得到

 5     1     5     1     5      1     5      1       
 0     1     0     0     0      0     0      0

并将其保存在内存中。但是当我使用这样的构造时:

List<string> lines=File.ReadLines(fileName);
foreach (string line in lines)
        {
            var words = line.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            foreach(string w in words)
                Console.Write("{0,6}", w);

            // filling out
            for (int i = words.Length; i < 8; i++)
                Console.Write("{0,6}", "0.");

            Console.WriteLine();
        }

我只在显示器上以所需格式打印文本。我怎样才能保存它List<string> newLines

4

3 回答 3

2

如果我们假设数据是等间距的(如您当前Write等所建议的那样,那么我会将其处理为字符

char[] chars = new char[49];
foreach(string line in File.ReadLines(path))
{
    // copy in the data and pad with spaces
    line.CopyTo(0, chars, 0, Math.Min(line.Length,chars.Length));
    for (int i = line.Length; i < chars.Length; i++)
        chars[i] = ' ';
    // check every 6th character - if space replace with zero
    for (int i = 1; i < chars.Length; i += 6) if (chars[i] == ' ')
        chars[i] = '0';
    Console.WriteLine(chars);
}

或者,如果您真的需要它作为行,请使用(在每次循环迭代结束时):

list.Add(new string(chars));
于 2013-03-26T08:22:52.957 回答
0

您可以使用此代码来产生您想要的结果:

StreamReader sr = new StreamReader("test.txt");
            string s;
            string resultText = "";
            while ((s = sr.ReadLine()) != null)
            {
                string text = s;
                string[] splitedText = text.Split('\t');
                for (int i = 0; i < splitedText.Length; i++)
                {
                    if (splitedText[i] == "")
                    {
                        resultText += "0 \t";
                    }
                    else
                    {
                        resultText += splitedText[i] + " \t";
                    }
                }
                resultText += "\n";
            }
            Console.WriteLine(resultText);

“test.txt”是包含您的文本的文本文件,“resultText”变量包含您想要的结果。

于 2013-03-26T08:55:05.977 回答
0

我假设数字之间正好有 5 个空格。所以这里是代码:

List<string> lines = System.IO.File.ReadLines(fileName).ToList();
List<string> output = new List<string>();

foreach (string line in lines)
{
    var words = 
        line.Split(new string[] { new string(' ', 5) },
                   StringSplitOptions.None).Select(input => input.Trim()).ToArray();

    Array.Resize(ref words, 8);

    words = words.Select(
                input => string.IsNullOrEmpty(input) ? "  " : input).ToArray();

    output.Add(string.Join(new string(' ', 5), words));
}

//output:
// 5     1     5     1     5      1     5      1       
// 0     1     0     0     0      0     0      0
于 2013-03-26T08:40:02.687 回答