2014-05-21 2 views
0

나는 C#에서이C#의 텍스트 파일에서 int []를 읽는 방법?

a 1 2 3 4 
b 4 6 7 8 
c 5 6 7 1 
... 

같은 텍스트 파일 "read.txt"가 나는 정의하고 싶습니다 :

int[] a = {1,2,3,4}; 
int[] b = {4, 6, 7, 8}; 
int[] c= {5, 6, 7, 1}; 
... 
내가 모든 라인을 읽고 넣어하는 방법을 물어보고 싶습니다

위의 C# 파일에

감사합니다.

+0

컴파일 타임에 C# 소스 파일을 생성하고 싶습니다. 맞습니까? – Constantin

답변

0

당신은 당신의 작업을 해결하기 위해 다음과 같은 방법을 사용할 수 있습니다

System.IO.File.ReadAllLines // Read all lines into an string[] 
string.Split     // Call Split() on every string and split by (white)space 
Int32.TryParse    // Converts an string-character to an int 

내가 거기에 먼저 List<int>Add() 모든 구문 분석 정수를 만들 것 ints의 배열을 만들 수 있습니다. 배열을 얻으려면 목록에 ToArray() 전화를 할 수 있습니다.

1

나는 정확한 목적이 무엇인지 모르겠지만, 내 생각이 같은 필요가 있습니다 :

public Dictionary<string, int[]> GetArraysFromFile(string path) 
{ 
    Dictionary<string, int[]> arrays = new Dictionary<string, int[]>(); 
    string[] lines = System.IO.File.ReadAllLines(path); 
    foreach(var line in lines) 
    { 
     string[] splitLine = line.Split(' '); 
     List<int> integers = new List<int>(); 
     foreach(string part in splitLine) 
     { 
      int result; 
      if(int.TryParse(part, out result)) 
      { 
       integers.Add(result); 
      } 
     } 
     if(integers.Count() > 0) 
     { 
      arrays.Add(splitLine[0], integers.ToArray()); 
     } 
    } 

    return arrays; 
} 

이 귀하의 첫 번째 문자는 문자/키 있다고 가정합니다. 문자가 키이고 값이 배열 인 사전이 있습니다.

관련 문제