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

   2024-10-22 3190
核心提示:在C#中可以使用IndexOf方法来查找字符串中指定字符的位置。例如,要查找字符串中第一次出现指定字符的位置,可以这样做:string

在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);}

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

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号