How can I find all indexes of a pattern in a string using c#?
For example I want to find all ## pattern indexes in a string like this 45##78$$#56$$JK01UU
How can I find all indexes of a pattern in a string using c#?
For example I want to find all ## pattern indexes in a string like this 45##78$$#56$$JK01UU
string pattern = "##"; string sentence = "45##78$$#56$$J##K01UU"; IList<int> indeces = new List<int>(); foreach (Match match in Regex.Matches(sentence, pattern)) { indeces.Add(match.Index); } indeces will have 2, 14
Edited the code to make it a cleaner function.
public IEnumerable<int> FindAllIndexes(string str, string pattern) { int prevIndex = -pattern.Length; // so we start at index 0 int index; while((index = str.IndexOf(pattern, prevIndex + pattern.Length)) != -1) { prevIndex = index; yield return index; } } string str = "45##78$$#56$$JK01UU"; string pattern = "##"; var indexes = FindAllIndexes(str, pattern); You can get all the indices of a pattern in a string by using a regex search like this.
string input = "45##78$$#56$$JK01UU", pattern = Regex.Escape("##"); Regex rx = new Regex(pattern); var indices = new List<int>(); var matches = rx.Matches(s); for (int i=0 ; i<matches.Length ; i++) { indices.Add(matches[i].Index); } Regex.Escape() on the pattern.Tested. Worked. But somewhat dumb.
string foo = "45##78$$#56$$JK01UU"; char[] fooChar = foo.ToCharArray(); int i = 0; bool register = false; foreach (char fc in fooChar) { if (fc == '#' && register == true) { MessageBox.Show("Index: " + (i-1)); } else if (fc == '#') { register = true; } else { register = false; } i++; }