阅读文本文件显示

时间:2015-01-21 09:23:14

标签: c# string console char ascii

早上好,我想知道如何做一件好事。我有一个.txt文件,其中的设计用ASCII表示。通过控制台我想读取此文件并在char类型的数组中添加任何ASCII字符。我怎么能知道读取我必须使用字符串的文件呢?我找到了这种方式,但我不知道如何使用char

class Program
    {
        static void Main(string[] args)
        {


            string[] lines = System.IO.File.ReadAllLines(@"best.txt");
            foreach (string line in lines)
            {

                Console.WriteLine("\t" + line);
            }

            Console.ReadLine();
        }
    }

1 个答案:

答案 0 :(得分:1)

嗯,你的问题还不够清楚......但是......我有这个吗? 是否要将文本文件中的所有字符映射到二维数组? 像这样:

[0, 0] = "a"
[0, 1] = "b"
[0, 2] = "c"
..<omited>..
[4, 0] = "x"
...
and so on...

一个小测试文本文件:

abcdefghij
1234567890
jihgfedcba
0987654321
xxxxxxxxxx
0000000000
yyyyyyyyyy
9999999999
----------
!!!!!!!!!!

C#代码:

static void Main()
{
    String input = File.ReadAllText(@"test.txt");   // read file content
    input = input.Replace("\r\n", "\n");            // get rid of \r

    int i = 0, j = 0;
    string[,] result = new string[10,10];           // hardcoded for testing purposes
    foreach (var row in input.Split('\n'))          // loop through each row
    {
        j = 0;
        foreach (var col in row.Select(c => c.ToString()).ToArray()) // split to array
        {                                                            // and loop through each char

            result[i, j] = col;                                      // Add the char to the jagged array => result
            j++;
        }
        i++;
    }
}


// EDIT: added some code to print out the result.
// Print all elements in the 2d array.
int rowLength = result.GetLength(0);
int colLength = result.GetLength(1);

for (int k = 0; k < rowLength; k++)
{
    for (int h = 0; h < colLength; h++)
    {
        Console.Write("{0} ", result[k, h]);
    }
    Console.Write(Environment.NewLine + Environment.NewLine);
}

我在这个例子中硬编码了数组的大小。