C# 返回字符串 string 中某一个字符第几次出现的位置所在的索引位置
// 返回 str 从前往后,第 count 次出现 ch 字符处的索引位置,失败返回 -1;
protected static int IndexOf(string str, char ch, int count)
{
if (count < 1)
{
return -1;
}
int index = -1;
for (int i = 0; i < count; ++i)
{
index = str.IndexOf(ch, ++index);
if (index == -1)
{
return -1;
}
}
return index;
}
// 返回 str 从后往前,第 count 次出现 ch 字符处的索引位置,失败返回 -1;
protected static int LastIndexOf(string str, char ch, int count)
{
if (count < 1)
{
return -1;
}
int index = str.Length;
for (int i = 0; i < count; ++i)
{
index = str.LastIndexOf(ch, --index);
if (index == -1)
{
return -1;
}
}
return index;
}
找到这个索引位置后,如果要截取字符串直接:str.Remove(index);
就可以了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了