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);就可以了。

posted @   double64  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示