string a="fafdsfds&vcdsvdsfdsjurysfds&qwewqewq&fdsfdsfdsgetretrsfds&7"如何知道第x个&的索引位置
除了indexof 还有其他更好的解决方法吗

解决方案 »

  1.   

    string a="fafdsfds&vcdsvdsfdsjurysfds&qwewqewq&fdsfdsfdsgetretrsfds&7";
    int n = 3;
    int x = 0;
    int i = 0;
    for (i = 0; i < a.Length && x < n; i++)
    {
        if (a[i] == '&') x++;
    }
    MessageBox.Show(i.ToString());
      

  2.   

    int n = 3;
    string a = "fafdsfds&vcdsvdsfdsjurysfds&qwewqewq&fdsfdsfdsgetretrsfds&7";
    int pos = a.Split('&').Take(n).Sum(x => x.Length) + n - 1;
    MessageBox.Show(pos.ToString());
      

  3.   

        protected void Page_Load(object sender, EventArgs e)
        {
            string a = "fafdsfds&vcdsvdsfdsjurysfds&qwewqewq&fdsfdsfdsgetretrsfds&7";        Response.Write(GetIndex(a, '&', 4));    }    public int GetIndex(string str , char c, int n)
        {
            int num = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (c != str[i]) continue;
                num++;
                if (num == n) return i;
            }
            return -1;
        }
      

  4.   

                string a = "fafdsfds&vcdsvdsfdsjurysfds&qwewqewq&fdsfdsfdsgetretrsfds&7";
                Regex regex = new Regex(@"&");
                MatchCollection match = regex.Matches(a);
                foreach (Match m in match)
                    foreach (Capture c in m.Groups[0].Captures)
                        Console.WriteLine(c.Index);
                Console.ReadLine();
      

  5.   

                string a = "fafdsfds&vcdsvdsfdsjurysfds&qwewqewq&fdsfdsfdsgetretrsfds&7";
                Regex regex = new Regex(@"&");
                MatchCollection match = regex.Matches(a);
                for (int j = 1; j <= match.Count;j++ )
                    if (j == 3)
                        Console.WriteLine(match[j-1].Groups[0].Captures[0].Index);
                Console.ReadLine();