如何找到一个字符在数组中第k次出现的位置?

How can I find the the position of the k-th occurrence of a character in an array?

本文关键字:位置 数组 何找 字符 一个      更新时间:2023-10-16

我正在写一个程序,它接受一个字符串,一个单个字符和一个整数k,然后它找到给定字符在给定字符串中出现的第k次

我认为代码是正确的,但是下面的代码没有给出正确的结果。

char ch[100];
char character;
int n;
cout << endl << "Type a string of characters : ";
gets_s(ch);
cout << endl << "Enter a single Character : ";
cin >> character;
cout << "Enter the event : ";
cin >> n;
if ( func_1( ch,  character,  n)!=-1)
    cout << endl << n << "th event is in the position number  " << (ch, character, n)<< endl;
else
    cout << "Event couldn't be found  ." << endl;
}
 int func_1(char ch[], char character, int n)
 {
    int i = 0;
    int c = 0;
    do
    {
       i++;
    } while (ch[i] != '');
    int j;
    for (j = 0; j < i-1;)
    {
        if (ch[j] == character)
            c = c + 1;
        j++;
    }
    if (c == n)
        return j-1;
    else
        return -1;
}

代码中有很多问题,但最相关的部分是这个:

for (j = 0; j < i-1;)
{
    if (ch[j] == character)
        c = c + 1;
    j++;
}
if (c == n)
    return j-1;
else
    return -1;

计算整个字符串中出现的次数,然后检查您是否足够幸运地得到整个字符串中所需的准确出现次数。

你真正想做的是检查是否在循环中发现第n次出现,如下所示:

for (j = 0; j < i-1;)
{
    if (ch[j] == character)
        c = c + 1;
    if (c == n)
        return j;  
    j++;
}

那么您可能想要阅读strlen, strchr,并修复代码中的其他错误。

func():

有几个错误

看:

do {
    i++;
} while (ch[i] != '');   // ouch will loop forever if ch[] is "" !! 

使用正常的while,或者写i=strlen(ch);

然后,当你写这个的时候,计算所有的出现次数:

for (j = 0; j < i - 1;) {   // loop unil end of string  
    if (ch[j] == character)
        c = c + 1;            // But if there are several occurences, he will count them all 
    j++;
}

例如,如果ch[]中有两个'e',并且您查找第一个出现,当循环结束时,c中将有两个'e',因此它将失败!

重写这个循环:

for (j = 0; j < i - 1 && c!=n;j++) {   // loop unil end of string => put j++ here for clarity, and exit if you've fount what you've searched
    if (ch[j] == character)
        c++;             
}

但是在主程序中也有一个显示问题。看:

if (func_1(ch, character, n) != -1)
    cout << endl << n << "th event is in the position number  " << (ch, character, n) << endl;

好吧,他会打印他找到了什么,但他总是打印n,因为(ch, character, n)不是一个函数调用,而是一个逗号操作符,它返回最右边的元素。

重写为:

int result = func_1(ch, character, n);
if (result != -1)
    cout << endl << n << "th event is in the position number  " << result << endl;