如何找到一个字符在数组中第k次出现的位置?
How can I find the the position of the k-th occurrence of a character in an array?
我正在写一个程序,它接受一个字符串,一个单个字符和一个整数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;
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 如何在数组中交换最小和最大的位置?
- C++ 2D 数组写入多个位置
- C++指针数组到字符数组中的特定位置
- 递增 'int i = 0' 以在初始化的字符数组的位置递增
- 数组中所有元素的最新最小元素的第五个位置
- 关于引用数组位置的问题
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 创建 2D 数组0xCCCCCCCC访问冲突写入位置
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 如何在 3x4 数组中随机 4 个不同的位置
- C++不同内存位置中的默认数组值
- 使用动态数组访问冲突写入位置
- C++访问冲突读取位置0xDDDDDDCD当我尝试删除已更新的数组时
- C++将可变数量的位置从给定数组传递到函数
- 在不同位置渲染相同精灵的数组
- 有没有办法汇总数组的位位置
- 如何查找数组中所有重复元素的位置
- 在给定的整数数组中,可以找到在给定位置之间分类数组的整数之和
- C++ 在不同位置具有不同数据类型的多维数组