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); }
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With