2010-03-10 1 views
0

색인을 찾기 위해 어디에서 검색을 계속합니까?색인을 찾기 위해 어디에서 검색을 계속합니까?

나는 파일에서 문자의 색인을 찾으려고합니다. 다음 문자의 색인을 찾으려면 거기에서 계속해야합니다. 예를 들어 문자열 "habcdefghij"그것, 그것은 두 번째 시간보다는 먼저 시간의 인덱스를 반환합니다 "cedef"

하지만 두 번째 검색은 파일의 시작 부분에서 시작을 반환해야하므로

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

입니다 경우 String.indexOf를 사용하는 경우 :-(

답변

4

당신은 시작 인덱스를 지정할 수 있습니다. 을 시도해보십시오

//... 
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

이 코드는 모든 일치 항목을 찾아 순서대로 표시합니다.

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