如何从那里我一直在寻找,找到指数继续?

我寻找在一个文件中找到字符的索引;然后,我不得不从那里继续寻找下一个字符的索引。例如:字符串是 “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: - (

有帮助吗?

解决方案

可以使用String.IndexOf当指定开始索引。 尝试

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

其他提示

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);

此代码查找所有匹配,并且示出了它们,以:

 // 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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top