2010-03-10 7 views
0

Comment continuer d'où j'ai cherché pour trouver l'index?Comment continuer d'où j'ai cherché pour trouver l'index?

Je cherche dans un fichier pour trouver l'index d'un caractère; alors je dois continuer à partir de là pour trouver l'index du personnage suivant. Par exemple: la chaîne est « 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); 

il devrait retourner « CEDEF »

mais la seconde recherche commence à partir du début du fichier, il retourne l'index de la première h plutôt que deuxième h :-(

Répondre

4

Vous pouvez spécifier un index de départ lors de l'utilisation String.indexOf. Essayez

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

Ce code trouve toutes les correspondances et les affiche dans l'ordre:

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