views:

44

answers:

3

How to continue from where I have been searching to find the index?

I am searching in a file to find the index of a character; then I have to continue from there to find the index of the next character. For example : string is " 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);

so it should return "cedef"

but the second search starts from the beginning of the file, it will return the index of first h rather than second h:-(

+3  A: 

You can specify a start index when using String.IndexOf. Try

//...
int indexend = message.IndexOf("h", index); 
//...
Jens
A: 
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);
TheMachineCharmer
A: 

This code finds all the matches, and shows them in order:

 // 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();
Javier Morillo