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

后端 未结 7 449
遇见更好的自我
遇见更好的自我 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 02:15
    public static String[] Split(this string s,char c = '\t')
        {
            if (s == null) return null;
            var a = new List<int>();
            int i = s.IndexOf(c);
            if (i < 0) return new string[] { s };
            a.Add(i);
            for (i = i+1; i < s.Length; i++) if (s[i] == c) a.Add(i);
            var result = new string[a.Count +1];            
            int startIndex = 0;
            result[0] = s.Remove(a[0]);
            for(i=0;i<a.Count-1;i++)
            {
                result[i + 1] = s.Substring(a[i] + 1, a[i + 1] - a[i] - 1);
            }
            result[a.Count] = s.Substring(a[a.Count - 1] + 1);
            return result;
        }
    
    0 讨论(0)
提交回复
热议问题