I have an extension method that I use for strings to get substring indices, since .Net provides only IndexOf (the only result for the first substring match).
public static class Extensions { public static int[] IndexesOf(this string str, string sub) { int[] result = new int[0]; for(int i=0; i < str.Length; ++i) { if(i + sub.Length > str.Length) break; if(str.Substring(i,sub.Length).Equals(sub)) { Array.Resize(ref result, result.Length + 1); result[result.Length - 1] = i; } } return result; } }
You can use the extension method for all instances of the print key.
int[] indexes = stringWithKeys.IndexesOf("key"); foreach(int index in indexes) {
I know that my sample code may be the longest, but the extension method can be reused, and you can put it in a utility-type library for future reference.
source share