首页主机资讯c#怎么查找字符串中指定字符的位置

c#怎么查找字符串中指定字符的位置

时间2024-05-28 07:54:03发布访客分类主机资讯浏览772
导读:在C#中可以使用IndexOf方法来查找字符串中指定字符的位置。例如,要查找字符串中第一次出现指定字符的位置,可以这样做: string str = "Hello World"; char searchChar = 'o'; int pos...

在C#中可以使用IndexOf方法来查找字符串中指定字符的位置。例如,要查找字符串中第一次出现指定字符的位置,可以这样做:

string str = "Hello World";
    
char searchChar = 'o';
    
int position = str.IndexOf(searchChar);


if (position != -1)
{

    Console.WriteLine("The position of '{
0}
' in the string is: {
1}
    ", searchChar, position);

}

else
{

    Console.WriteLine("The character '{
0}
    ' was not found in the string.", searchChar);

}
    

如果要查找字符串中最后一次出现指定字符的位置,可以使用LastIndexOf方法:

string str = "Hello World";
    
char searchChar = 'o';
    
int position = str.LastIndexOf(searchChar);


if (position != -1)
{

    Console.WriteLine("The last position of '{
0}
' in the string is: {
1}
    ", searchChar, position);

}

else
{

    Console.WriteLine("The character '{
0}
    ' was not found in the string.", searchChar);

}
    

这样就可以查找字符串中指定字符的位置了。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c#怎么查找字符串中指定字符的位置
本文地址: https://pptw.com/jishu/669770.html
python如何打印对象所有属性 mysql怎么查询不为空的数据

游客 回复需填写必要信息