【发布时间】:2014-08-13 14:59:12
【问题描述】:
我正在编写一个程序,它接受一个字符串、一个字符和一个整数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;
}
【问题讨论】:
-
你是什么意思:“这个整数表示该单个字符发生在数组块中的事件”?我完全不知道这应该是什么意思。
-
@JerryCoffin 例如,您的字符串是:Jerry Coffin 您的单个字符是:f 您的整数是:2 结果必须是第二个“f”位于数组的第 10 个块中。
-
也许我今天早上速度很慢,但这似乎并不能说明什么。
-
你要的词不是“事件”,而是“发生”,可能会让一些人头疼:)
-
所以,给定一个字符串 s,一个字符 c 和一个整数 k,你想找到索引k: c 在s 中的第一次出现?如果我是你,我会首先解决找到第一个出现的问题。然后考虑如何循环该解决方案。