Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way to get all indexes of a character in a string

Tags:

c#

Instead of looping through each character to see if it's the one you want then adding the index your on to a list like so:

     var foundIndexes = new List<int>();      for (int i = 0; i < myStr.Length; i++)      {         if (myStr[i] == 'a')            foundIndexes.Add(i);      } 
like image 297
Mark W Avatar asked Oct 07 '12 03:10

Mark W


People also ask

How do you get all indexes of a character in a string?

1. Using indexOf() and lastIndexOf() method. The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.

How do you find the index of a particular character or a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the index of a particular character in a string in JavaScript?

JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.


2 Answers

You can use String.IndexOf, see example below:

    string s = "abcabcabcabcabc";     var foundIndexes = new List<int>();      long t1 = DateTime.Now.Ticks;     for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))         {          // for loop end when i=-1 ('a' not found)                 foundIndexes.Add(i);         }     long t2 = DateTime.Now.Ticks - t1; // read this value to see the run time 
like image 88
m.zam Avatar answered Sep 20 '22 22:09

m.zam


I use the following extension method to yield all results:

public static IEnumerable<int> AllIndexesOf(this string str, string searchstring) {     int minIndex = str.IndexOf(searchstring);     while (minIndex != -1)     {         yield return minIndex;         minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);     } } 

usage:

IEnumerable<int> result = "foobar".AllIndexesOf("o"); // [1,2] 

Side note to a edge case: This is a string approach which works for one or more characters. In case of "fooo".AllIndexesOf("oo") the result is just 1 https://dotnetfiddle.net/CPC7D2

like image 35
fubo Avatar answered Sep 21 '22 22:09

fubo