How to find all the indexes of the substring in the string, while not changing the string itself?

  • Regularly. There matches contain a position. - vitidev
  • on another it is impossible? - Draktharon

2 answers 2

You can use the IndexOf() overload, which accepts an initial index:

 string source = "some source string"; string substring = "so"; var indices = new List<int>(); int index = source.IndexOf(substring, 0); while (index > -1) { indices.Add(index); index = source.IndexOf(substring, index + substring.Length); } 
  • Endless cycle. The index variable will always be greater than -1, since it does not change - Draktharon
  • one
    @RustemValeev fixed. - andreycha

The extension method for finding all indexes of occurrence will do a good job with this task:

 public static List<int> AllIndexesOf(this string str, string value) { if (String.IsNullOrEmpty(value)) throw new ArgumentException("the string to find may not be empty", "value"); List<int> indexes = new List<int>(); for (int index = 0;; index += value.Length) { index = str.IndexOf(value, index); if (index == -1) return indexes; indexes.Add(index); } } 

Using the method is quite simple:

 string dummyText = "blabla"; string substring = "b"; List<int> indexes = dummyText .AllIndexesOf(substring); 

The main thing to remember to put this method in a static class and specify the namespace.