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

数字の間にちょうど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 に答える
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 に答える