📌  相关文章
📜  查找给定字符串中出现的第 N 个字符

📅  最后修改于: 2021-09-06 11:27:52             🧑  作者: Mango

给定字符串str 、字符ch和值N ,任务是找到给定字符在给定字符串第 N 次出现的索引。如果不存在这种情况,则打印 -1。

例子:

方法:

  • 横越字符字符串的字符。
  • 检查每个字符是否与给定字符匹配。
  • 如果与给定的字符匹配,则将计数增加 1。
  • 如果计数变为等于 N,则返回最新找到的索引
  • 如果遍历后count与N不匹配,返回-1

下面是上述方法的实现:

C++
// C++ implemenation to find the
// Nth occurrence of a character
 
#include 
using namespace std;
 
// Function to find the
// Nth occurrence of a character
int findNthOccur(string str,
                 char ch, int N)
{
    int occur = 0;
 
    // Loop to find the Nth
    // occurence of the character
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == ch) {
            occur += 1;
        }
        if (occur == N)
            return i;
    }
    return -1;
}
 
// Driver Code
int main()
{
    string str = "geeks";
    char ch = 'e';
    int N = 2;
    cout << findNthOccur(str, ch, N);
}


Java
// Java implemenation to find the
// Nth occurrence of a character
import java.util.*;
 
class GFG
{
 
// Function to find the
// Nth occurrence of a character
static int findNthOccur(String str,
                    char ch, int N)
{
    int occur = 0;
 
    // Loop to find the Nth
    // occurence of the character
    for (int i = 0; i < str.length(); i++)
    {
        if (str.charAt(i) == ch)
        {
            occur += 1;
        }
        if (occur == N)
            return i;
    }
    return -1;
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "geeks";
    char ch = 'e';
    int N = 2;
    System.out.print(findNthOccur(str, ch, N));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 implemenation to find the
# Nth occurrence of a character
 
# Function to find the
# Nth occurrence of a character
def findNthOccur(string , ch, N) :
    occur = 0;
 
    # Loop to find the Nth
    # occurence of the character
    for i in range(len(string)) :
        if (string[i] == ch) :
            occur += 1;
 
        if (occur == N) :
            return i;
     
    return -1;
 
# Driver Code
if __name__ == "__main__" :
 
    string = "geeks";
    ch = 'e';
    N = 2;
    print(findNthOccur(string, ch, N));
 
# This code is contributed by AnkitRai01


C#
// C# implemenation to find the
// Nth occurrence of a character
using System;
 
class GFG
{
 
// Function to find the
// Nth occurrence of a character
static int findNthOccur(String str,
                    char ch, int N)
{
    int occur = 0;
 
    // Loop to find the Nth
    // occurence of the character
    for (int i = 0; i < str.Length; i++)
    {
        if (str[i] == ch)
        {
            occur += 1;
        }
        if (occur == N)
            return i;
    }
    return -1;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "geeks";
    char ch = 'e';
    int N = 2;
    Console.Write(findNthOccur(str, ch, N));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
2

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live