在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);
}
这样就可以查找字符串中指定字符的位置了。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/984998.html