Pergunta

Como continuar de onde eu fui pesquisar para encontrar o índice?

Eu estou procurando em um arquivo para encontrar o índice de um personagem; então eu tenho que continuar a partir daí para encontrar o índice do próximo personagem. Por exemplo: string é "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);

para que ele deve retornar "CEDEF"

Mas a segunda busca começa a partir do início do arquivo, ele irá retornar o índice do primeiro h em vez de segunda h: - (

Foi útil?

Solução

Você pode especificar um índice inicial ao usar String.IndexOf. Tentar

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

Outras dicas

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

Este código encontra todos os jogos, e mostra-los em ordem:

 // 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();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top