读取所有行到字符串[]直到找到下一个符号

时间:2018-02-05 22:25:59

标签: c# system.io.file file.readalllines

我正在尝试读取一个文本文件(每个条目一行,用两个“enums”分隔,用作属性,参见示例)。

[enum1_0][enum2_0]
line
line

[enum1_0][enum2_1]
line
line

[enum1_1][enum2_0]
line
line

[enum1_1][enum2_1]
line
line

我想创建一个存储所有这些字符串的string[][][],以便我以后可以使用这样的方法轻松检索它们,但是我在语法方面遇到了很多麻烦以及如何识别标志文本文件中的属性:

public static string GetRandomString(Enum1 e1, Enum2 e2)
{
    return _strings[(int)e1][(int)e2][_random.Next(0, length)];
}

澄清一下:我有一个文本文件,每行有一个条目,其中行块由“[]”分隔 - 标记为'符号',对应于MyEnum1和MyEnum2的每个索引。

我正在尝试将所有字符串读入单个字符串[],然后使用System.File.IO.ReadAllLines将它们排序为字符串[] [] [],以便稍后我可以使用上面显示的函数使用我的枚举来检索它们。

1 个答案:

答案 0 :(得分:0)

所以,经过适当的睡眠后,我重新考虑了我的结构,这是我的解决方案:

static List<GovermentData> _data = new List<GovermentData>();

static string[] _all = File.ReadAllLines(@"Assets/Resources/" + PREFIXES_FILEPATH + ".txt");
static string[] _nations = File.ReadAllLines(@"Assets/Resources/" + NAMES_FILEPATH + ".txt");

public static void Initialize()
{
    EconomicPolicy ep = EconomicPolicy.RadicalCollectivist;
    TechLevel tl = TechLevel.Ancient;

    //iterate all prefixes
    for (int i = 0; i < _all.Length; i++)
    {
        if (_all[i].Length <= 0)
            continue;

        if(_all[i].StartsWith("["))
        {
            string s = _all[i];

            //remove first [ and last ]
            s = s.Remove(0, 1);
            s = s.Remove(s.Length - 1, 1);

            //split on ][
            string[] r = s.Split(new string[] { "][" }, StringSplitOptions.None);

            ep = (EconomicPolicy)Enum.Parse(typeof(EconomicPolicy), r[0]);
            tl = (TechLevel)Enum.Parse(typeof(TechLevel), r[1]);
        }
        else
            _data.Add(new GovermentData(_all[i], ep, tl));
    }
}
public static string GetCivilisationName(EconomicPolicy ep, TechLevel t)
{
    GovermentData[] gd = _data.FindAll(d => d.economicPolicy == ep && d.techLevel == t).ToArray();

    if(gd.Length >= 1)
        return gd[0].name + " of " + _nations[_random.Next(0, _nations.Length)];
    else
        return gd[_random.Next(0, gd.Length)].name + " of " + _nations[_random.Next(0, _nations.Length)];
}

public struct GovermentData
{
    public readonly string name;
    public readonly EconomicPolicy economicPolicy;
    public readonly TechLevel techLevel;

    public GovermentData(string name, EconomicPolicy economicPolicy, TechLevel techLevel)
    {
        this.name = name;
        this.economicPolicy = economicPolicy;
        this.techLevel = techLevel;
    }
}

感谢尽管我自己有困惑但仍试图帮助我。