C#检索出一个字符串中某字符第n次出现的位置(IndexOf)的代码

在开发过程中,将开发过程中经常用的一些代码片段做个记录,下面资料是关于C#检索出一个字符串中某字符第n次出现的位置(IndexOf)的代码,应该是对各位有较大用处。
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Please input your STRING:”);
string a = Console.ReadLine();
char c;
char find_c;
Console.WriteLine(“Please input the CHARACTER in your string:”);
find_c = Convert.ToChar(Console.ReadLine());
int count = 0;
for (int i = 0; i < a.Length; i++)
{
c = a[i];
{
count++;
}
}
Console.WriteLine(“There are total {0} of char ‘{1}’ in your input string.”,count,find_c);
int index = 0;
Console.WriteLine(“Please input the SEQUENCE of the char ‘{0}’ in your input string:”, find_c);
n = Convert.ToInt32(Console.ReadLine());
if (n > count)
{
Console.WriteLine(“Error:The Num must be less than or equal to {0}.”,count);
Console.ReadKey();
return;
}
for (int j = 1; j <= count; j++)
{
index = a.IndexOf(find_c,index);
if (j == n)
{
break;
}
else
{
index = a.IndexOf(find_c,index+1);
}

        }
        Console.WriteLine("The Index of the No.{0} char '{1}' in your input string is {2}.", n, find_c, index);
        Console.ReadKey();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44281775/article/details/88862035