简体   繁体   中英

how to find indexof substring in a text file

I have converted an asp.net c# project to framework 3.5 using VS 2008. Purpose of app is to parse a text file containing many rows of like information then inserting the data into a database.

I didn't write original app but developer used substring() to fetch individual fields because they always begin at the same position.

My question is:

What is best way to find the index of substring in text file without having to manually count the position? Does someone have preferred method they use to find position of characters in a text file?

I would say IndexOf() / IndexOfAny() together with Substring() . Alternatively, regular expressions . It the file has an XML-like structure, this .

If the files are delimited eg with commas you can use string.Split

If data is: 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;
    }
}

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

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

The text file I'm reading does not contain delimiters - sometimes there spaces between fields and sometimes they run together. In either case, every line is formatted the same. When I asked the question I was looking at the file in notepad.

Question was: how do you find the position in a file so that position (a number) could be specified as the startIndex of my substring function?

Answer: I've found that opening the text file in notepad++ will display the column # and line count of any position where the curser is in the file and makes this job easier.

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