【问题标题】:C# Parsing Text File and retrieving string/floatC# 解析文本文件并检索字符串/浮点数
【发布时间】:2013-12-12 22:47:15
【问题描述】:
foreach (string line in File.ReadAllLines(openBunkerDialog.FileName))
{
    if (line.Contains("crate(") && line.Contains(");"))
    {
        string x = line.Substring(line.IndexOf("crate("), line.IndexOf(","));
        string y = line.Substring(line.IndexOf("crate(") + line.IndexOf(x), line.IndexOf(",") + line.IndexOf(x));
        string z = line.Substring(line.IndexOf("crate(") + line.IndexOf(x) + line.IndexOf(y), line.IndexOf(",") + line.IndexOf(x) + line.IndexOf(y));
        x = x.Replace("crate(", string.Empty);
        y = y.Replace("crate(", string.Empty);
        z = z.Replace("crate(", string.Empty);
        MessageBox.Show("X: " + x + " Y: " + y + " Z: " + z);
        //EntitySpawning.crate(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z), false);
    }
    else if (line.Contains("entity(") && line.Contains(");"))
    {
    }
}

我想读取一个文件并从该行中获取信息。 文本文件示例:

crate(23231, 243243, 123324); 
crate(45678, 987532, 1234); 
etc...

我想获取用户输入的那些 x/y/z 值,但是怎么做??? 如果有人可以提供帮助,谢谢

【问题讨论】:

  • 如果文件中的所有行都与您放置的一样,则拆分字符串(检查字符串的部分是否以 x、y、z 开头,然后删除尾随)并再次拆分, - 这就是艰难的方式。简单的方法是使用正则表达式来提取值
  • 每行包含 1 个 create (x, y, z) 还是一行中有多个?
  • 不只有 1 个 crate(x, y, z);排成一行
  • 你能把你的行作为文本的例子吗
  • 板条箱(23231, 2432343, 1234324);

标签: c# file parsing text


【解决方案1】:

这是一个可能的实现。使用IndexOf,不带和带起始索引、String.SubstringString.Split。最后,您可以使用float.TryParse 安全地解析括号中的前三个标记。

foreach (string line in File.ReadAllLines(openBunkerDialog.FileName))
{
    int index = line.IndexOf("crate(");
    if (index >= 0)
    {
        index += "crate(".Length;
        int endIndex = line.IndexOf(")", index);
        if (endIndex >= 0)
        {
            string inParentheses = line.Substring(index, endIndex - index);
            string[] all = inParentheses.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if(all.Length >= 3)
            {
                float x, y, z;
                float.TryParse(all[0].Trim(), out x);
                float.TryParse(all[1].Trim(), out y);
                float.TryParse(all[2].Trim(), out z);
            }
        }
    }
}

您也可以使用正则表达式方法,但如果可能,我会使用高效的字符串方法。

【讨论】:

    【解决方案2】:

    嗯,你很接近。您要做的是获取crate( 的索引,然后获取); 的索引。然后你取这两个索引之间的子字符串并用逗号分割。您也可以使用正则表达式。

    【讨论】:

    • 谢谢...但是下面的人打败了你:(
    猜你喜欢
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2017-09-30
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多