简体   繁体   中英

Reading from txt file to array/list<>

I need to read all of .txt file and save data to array/list. File looks like this:

row11    row12    row13
row21    row22    row23
row31    row32    row33

between strings are only spaces.

Next I will insert data from array/list<> to mysql, but it is not problem. Thanks.

EDIT: I need insert 3 columns to mysql like .txt file.

Use String.Split(Char[], StringSplitOptions) where the first parameter specifies that you want to split your string using spaces and tabs, and the second parameter specifies that you ignore empty entries (for cases where there are multiple spaces between entries)

Use this code:

var lines = System.IO.File.ReadAllLines(@"D:\test.txt");
var data = new List<List<string>>();
foreach (var line in lines)
{
    var split = line.Split(new[]{' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
    data.Add(split.ToList());
}

You can use File.ReadLines() to read the lines from the file, and then Regex.Split() to split each line into multiple strings:

static IEnumerable<String> SplitLines(string path, string splitPattern)
{
    foreach (string line in File.ReadAllLines(path))
        foreach (string part in Regex.Split(line, splitPattern))
            yield return part;
}

To split by white space, you can use the regex pattern \\s+ :

var individualStrings = SplitLines(@"C:\path\to\file.txt", @"\s+");

You can use the ToList() extension method to convert it to a list:

List<string> individualStrings = SplitLines(@"D:\test\rows.txt", @"\s+").ToList();

As long as there are never spaces in the "values", then a simple line-by line parser will work.

A simple example

var reader = new StreamReader(filePath);

var resultList = new List<List<string>>();

string line;

while ((line = reader.ReadLine()) != null)
{
    var currentValues = new List<string>();

    // You can also use a StringBuilder
    string currentValue = String.Empty;

    foreach (char c in line)
    {
        if (Char.IsWhiteSpace(c))
        {
            if (currentValue.Length > 0)
            {
                currentValues.Add(currentValue);

                currentValue = String.Empty;
            }
            continue;
        }

        currentValue += c;
    }

    resultList.Add(currentValues);
}

这是一个基于Amadeusz答案的漂亮单线:

var lines = File.ReadAllLines(fileName).Select(l => l.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)).SelectMany(words => words);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM