C# 返回字符串 string 中某一个字符第几次出现的位置所在的索引位置

发布时间 2023-12-26 13:58:05作者: double64
 // 返回 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);就可以了。