5

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

6
  • How do you define a "pattern"? Commented May 11, 2012 at 6:15
  • Have you tried anything? Have you tried Regular Expressions? Commented May 11, 2012 at 6:15
  • 1
    Could you show some input strings and intended output ? Commented May 11, 2012 at 6:15
  • input pattern is ## string is 45##78$$#56$$JK01UU Commented May 11, 2012 at 6:15
  • string SearchPattern = "##"; string Str = "45##78$$#56$$JK01UU"; Commented May 11, 2012 at 6:17

5 Answers 5

9
 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

Sign up to request clarification or add additional context in comments.

1 Comment

or in 1 line: var indexes = Regex.Matches(_msg, pattern).Select(x => x.Index).ToList();
3

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

1 Comment

I guess this must be faster than the answers that use regex. Would be nice to have some profiling results.
2

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); } 

1 Comment

You probably need to run Regex.Escape() on the pattern.
0

Another one that tries to be efficient:

public IEnumerable<int> FindPatternIndexes(string input, string search) { var sb = new StringBuilder(input); for (var i = 0; search.Length <= sb.Length; i++) { if (sb.ToString().StartsWith(search)) yield return i; sb.Remove(0,1); } } 

Comments

0

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++; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.