0
点赞
收藏
分享

微信扫一扫

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

westfallon 2024-01-03 阅读 12

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



举报

相关推荐

0 条评论