2015-01-21 78 views
0

早上好,我想知道我該如何做一件善意的事情。我有一個.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(); 
     } 
    } 
+0

請問您可以在這裏發佈您的.txt文件嗎? – Sandip 2015-01-21 09:26:00

+0

這是我在.txt文件中的一個例子 – user3223680 2015-01-21 09:30:37

+0

我已經讀了三次你的問題,我無法弄清楚你到底在問什麼。 – Dennisch 2015-01-21 09:32:54

回答

1

嗯,你的問題是不夠清楚..但是..我有這個權利?
是否要將文本文件中的所有字符映射到2d數組?
事情是這樣的:

[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); 
} 

我硬編碼數組的大小在這個例子中。