读取具有特定结构的文本文件

本文关键字:文本 文件 结构 读取 | 更新日期: 2023-09-27 18:10:27

我有一个*.txt文件,结构如下:

"thing 1" "thing 2" "thing 3" "thing 4"
"thing 6" "thing 7" "thing 8" "thing 9"
"thing 10" "thing 11" "thing 12" "thing 13"
"thing 14" "thing 15" "thing 16" "thing 17"
...

我如何从文本文件中提取它,这样我就可以有一些字符串,与事物1的值,事物2,等等。

我只能一次读完整个文件。或者有另一种方式,如何存储一些"数据库"数据(也许excel文件?)?

读取具有特定结构的文本文件

这是一个非正则表达式解决方案。这将给你一个字符串数组。

using System;
using System.Linq;
using System.Reflection;
public class Program
{
    public static void Main()
    {
        String input = "'"thing 1'" '"thing 2'" '"thing 3'" '"thing 4'"";
        var result = input.Split(new char[]{''"'}).Where(p=> !String.IsNullOrWhiteSpace(p));
        foreach(string v in result)
            Console.WriteLine(v);
    }
}

这是基本的c#文件IO,实际上并不是针对Xamarin或Android的。

请注意,有很多方法可以做到这一点,这只是一种方法。

// File classes are all in System.IO
// read each line as a string, put it into a list
List<string> data = File.ReadLines(path)
foreach(string s in data) {
  // s is one line of data
  // use Regex to grab each string (System.Text.RegularExpressions)
  foreach(Match match in Regex.Matches(inputString, "'"([^'"]*)'""))
    // match.Value should be the individual value "thing 1", etc
    // you can strip off the "" if you want and then put into your DB
    // or whatever you want to do with it 
  }
}