【问题标题】:How to continue from where I have been searching to find the index?如何从我一直在搜索的位置继续查找索引?
【发布时间】:2010-03-10 15:00:40
【问题描述】:

如何从我一直在搜索的位置继续查找索引?

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

【问题讨论】:

    标签: c# .net string indexof


    【解决方案1】:

    您可以在使用 String.IndexOf 时指定起始索引。 试试

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

    【讨论】:

      【解决方案2】:
      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);
      

      【讨论】:

        【解决方案3】:

        此代码查找所有匹配项,并按顺序显示:

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

        【讨论】:

          猜你喜欢
          • 2021-11-19
          • 1970-01-01
          • 1970-01-01
          • 2021-02-21
          • 2012-11-18
          • 2022-01-07
          • 2010-11-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多