0

如何从我一直在搜索的位置继续查找索引?

我正在文件中搜索以查找字符的索引;然后我必须从那里继续找到下一个字符的索引。例如:字符串是“habcdefghij”

       int index = message.IndexOf("c");
        Label2.Text = index.ToString();
        label1.Text = message.Substring(index);
        int indexend = message.IndexOf("h");
        int indexdiff = indexend - index;
       Label3.Text = message.Substring(index,indexdiff);

所以它应该返回“cedef”

但是第二次搜索从文件的开头开始,它将返回第一个 h 的索引而不是第二个 h:-(

4

3 回答 3

4

使用 String.IndexOf 时可以指定起始索引。尝试

//...
int indexend = message.IndexOf("h", index); 
//...
于 2010-03-10T15:05:22.123 回答
0
int index = message.IndexOf("c");
label1.Text = message.Substring(index);

int indexend = message.IndexOf("h", index); //change

int indexdiff = indexend - index;
Label3.Text = message.Substring(index, indexdiff);
于 2010-03-10T15:08:52.227 回答
0

此代码查找所有匹配项,并按顺序显示它们:

 // Find the full path of our document
        System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);            
        string path = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "MyTextFile.txt");

    // Read the content of the file
    string content = String.Empty;
    using (StreamReader reader = new StreamReader(path))
    {
        content = reader.ReadToEnd();
    }

    // Find the pattern "abc"
    int index = content.Length - 1;

    System.Collections.ArrayList coincidences = new System.Collections.ArrayList();

    while(content.Substring(0, index).Contains("abc"))
    {
        index = content.Substring(0, index).LastIndexOf("abc");
        if ((index >= 0) && (index < content.Length - 4))
        {
            coincidences.Add("Found coincidence in position " + index.ToString() + ": " + content.Substring(index + 3, 2));                    
        }
    }

    coincidences.Reverse();

    foreach (string message in coincidences)
    {
        Console.WriteLine(message);
    }

    Console.ReadLine();
于 2010-03-10T16:12:39.300 回答