【问题标题】:What's the best way to get all index values of a string in a string [duplicate]获取字符串中字符串的所有索引值的最佳方法是什么[重复]
【发布时间】:2016-04-05 01:42:23
【问题描述】:

我想在其父字符串中获取字符串的索引值,但big_string.IndexOf("small_string") 只返回它找到的第一个字符串的索引。 例如:

string big_string   = "sabcdaskdeweusdahsabchdjuasdabc";
string small_string = "abc";
int position;

position = big_string.IndexOf(small_string);

// Output: => 1;

big_string 中还有另外 2 个abc IndexOf 无法返回值。 如果我创建一个新的big_string 并消除它的第一个abc,我只能获得该值,将位置添加到列表中然后循环直到没有abc 离开。

我认为这不是获取字符串中子字符串的所有索引值的最佳方法。如果我不想使用循环和子字符串。我该怎么做?

这里有没有人知道实现目的的更好方法?

【问题讨论】:

标签: c# string


【解决方案1】:

您可以使用正则表达式。匹配对象将包含所有捕获并且每个捕获都有索引 https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.capture(v=vs.110).aspx

【讨论】:

    【解决方案2】:

    你可以用正则表达式来做到这一点-

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
    
        static void Main()
        {
            string big_string = "sabcdaskdeweusdahsabchdjuasdabc";
            string small_string = "abc";
    
            foreach (Match m in Regex.Matches(big_string, small_string))
            {
                Console.WriteLine(m.Index);
            }
    
            Console.Read();
        }
    }
    

    【讨论】:

      【解决方案3】:

      另一个有趣的解决方案:

      public static IEnumerable<int> FindIndexes(string text, string query)
      {
          return Enumerable.Range(0, text.Length - query.Length)
              .Where(i => query.Equals(text.Substring(i, query.Length));
      }
      

      从这里:C# - Finding All Indices of a Substring

      【讨论】:

        【解决方案4】:

        最快的方法总是循环,但你不需要子串:

        var myString = "myteststring";
        var search = "s";
        var indexes = new List<int>();
        var index = myString.IndexOf(search, 0);
        
        while (index != -1)
        {
            indexes.Add(index);
            index = myString.IndexOf(search, index + 1);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多