【问题标题】:how to find indexof substring in a text file如何在文本文件中查找子字符串的索引
【发布时间】:2013-01-18 00:19:55
【问题描述】:

我已经使用 VS 2008 将一个 asp.net c# 项目转换为 framework 3.5。应用程序的目的是解析一个包含许多行类似信息的文本文件,然后将数据插入到数据库中。

我没有编写原始应用程序,但开发人员使用 substring() 来获取单个字段,因为它们总是从同一位置开始。

我的问题是:

在文本文件中查找子字符串索引而无需手动计算位置的最佳方法是什么?有人有他们用来查找文本文件中字符位置的首选方法吗?

【问题讨论】:

  • 我想推荐正则表达式REGEX

标签: c# substring


【解决方案1】:

我会说IndexOf() / IndexOfAny()Substring()。或者,regular expressions。如果文件具有类似 XML 的结构,this

【讨论】:

    【解决方案2】:

    如果文件是用逗号分隔的,你可以使用 string.Split

    如果数据是:string[] text = { "1, apple", "2, orange", "3, lemon" };

        private void button1_Click(object sender, EventArgs e)
        {
            string[] lines = this.textBoxIn.Lines;
            List<Fruit> fields = new List<Fruit>();
            foreach(string s in lines)
            {
                char[] delim = {','}; 
                string[] fruitData = s.Split(delim);
                Fruit f = new Fruit();
                int tmpid = 0;
                Int32.TryParse(fruitData[0], out tmpid);
                f.id = tmpid;
                f.name = fruitData[1];
                fields.Add(f);
            }
            this.textBoxOut.Clear();
            string text=string.Empty;
            foreach(Fruit item in fields)
            {
                text += item.ToString() + " \n";
            }
            this.textBoxOut.Text = text;
        }
    }
    

    【讨论】:

      【解决方案3】:

      我正在阅读的文本文件不包含分隔符 - 有时字段之间有空格,有时它们一起运行。在任何一种情况下,每一行的格式都相同。当我问这个问题时,我正在记事本中查看文件。

      问题是:如何在文件中找到位置,以便可以将位置(数字)指定为我的子字符串函数的 startIndex?

      回答:我发现在 notepad++ 中打开文本文件会显示光标在文件中任何位置的列# 和行数,从而使这项工作更容易。

      【讨论】:

        【解决方案4】:

        您可以使用 indexOf() 然后使用 Length() 作为第二个子字符串参数

        substr = str.substring(str.IndexOf("."), str.Length - str.IndexOf("."));
        

        【讨论】:

          猜你喜欢
          • 2018-10-26
          • 2020-01-10
          • 1970-01-01
          • 1970-01-01
          • 2018-05-18
          • 2015-07-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多