C# split textfile into a 2 dimensional string arra

2019-07-07 05:10发布

I have a textfile that looks like this :

John,Gauthier,blue,May
Henry,Ford,Red,June
James,Bond,Orange,December

I want to split it into a two dimensional string array so I could separate each lines then each words. Ex:

mystring[0][0] = "John"
mystring[1][3] = "June"
mystring[2][2] = "Orange"

Here's what I did right now:

string[] words = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");

while (fichier.Peek() != -1)
{
  i++;
  words = myfile.ReadLine().Split(',');

}

I'm stuck. I'm able to split it into a one dimensional string array but not into a two dimensional string array. I guess I need to split it two times ; First time with '\n' and the second time with ',' and then put those two together.

3条回答
小情绪 Triste *
2楼-- · 2019-07-07 06:07

Try this

   var str = File.ReadAllText("myfile.csv");


 var arr = str.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

   var multi = arr.Select(x => x.Split(',')).ToArray();
查看更多
Fickle 薄情
3楼-- · 2019-07-07 06:11

Try:

var First = new string [100];
var Sec = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");

while (fichier.Peek() != -1)
{
  i++;
  var buff = myfile.ReadLine().Split(',');
  First[i] = buff[0];
  Sec[i] = buff[1];
}

Other idea, use a XML serilizer to serilize your hole Object. Two extensions for this:

    public static void SaveAsXML(this Object A, string FileName)
    {
        var serializer = new XmlSerializer(A.GetType());
        using (var textWriter = new StreamWriter(FileName))
        {
            serializer.Serialize(textWriter, A);
            textWriter.Close();
        }
    }

    public static void LoadFromXML(this Object A, string FileName)
    {
        if (File.Exists(FileName))
        {
            using (TextReader textReader = new StreamReader(FileName))
            {
                XmlSerializer deserializer = new XmlSerializer(A.GetType());
                A = (deserializer.Deserialize(textReader));
            }
        }
    }

Add than in any Static class and call:

YourSaveClassWhitchContainsYourArray.SaveAsXML("Datastore.xml");

or

YourSaveClassWhitchContainsYourArray.LoadFromXML("Datastore.xml");
查看更多
何必那么认真
4楼-- · 2019-07-07 06:14

This is actually a one-liner:

File.ReadLines("myfilename.txt").Select(s=>s.Split(',')).ToArray()

Since this is a beginner question, here's what's going on:

File.ReadLines(filename) returns a collection of all lines in your text file

.Select is an extension method that takes a function

s=>s.Split(',') is the function, it splits the string s by all commas and returns an array of strings.

.ToArray() takes the collection of string arrays created by .Select and makes an array out of that, so you get array of arrays.

查看更多
登录 后发表回答