我正在编写一个程序,它接受一个字符串,一个字符和一个整数 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] != '\0');
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;
}
答案 0 :(得分:0)
func():
中存在一些错误看看:
do {
i++;
} while (ch[i] != '\0'); // ouch will loop forever if ch[] is "" !!
使用正常时间,或写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++;
}
例如,如果有两个&#39; e&#39;在ch []中你找到第一次出现,当循环结束时,c中会有2,所以它会失败!
重写此循环:
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;
答案 1 :(得分:0)
嗯,代码中有很多问题,但最相关的部分就是这个:
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++;
}