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

后端 未结 7 555
遇见更好的自我
遇见更好的自我 2020-12-04 01:41

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&         


        
7条回答
  •  情书的邮戳
    2020-12-04 01:49

    You can use String.IndexOf, see example below:

        string s = "abcabcabcabcabc";
        var foundIndexes = new List();
    
        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
    

提交回复
热议问题