我正在尝试找出一种方法来完成这项工作:
//Returns a pointer to the nth char in a string
const char *nth_strchr(const char *s, int c, int n) {
int c_count = 0;
char *nth_ptr;
while (c_count++ != n) {
nth_ptr = strchr(s, c);
//need a line here to skip past the previous found occurrence.
}
return nth_ptr;
}
我不太确定如何做到这一点,以便 while
循环的每次迭代都可以确认上一个循环中找到的字符的出现/位置。由于我有指向第一次出现的指针...我正在考虑使用内存地址来递增下一个循环,以便我可以为下一个 strchr()
调用提供从 开始的字符串>c + 1
位置?
这可能吗?
最佳答案
const char* nth_strchr(const char* s, int c, int n)
{
int c_count;
char* nth_ptr;
for (c_count=1,nth_ptr=strchr(s,c);
nth_ptr != NULL && c_count < n && c!=0;
c_count++)
{
nth_ptr = strchr(nth_ptr+1, c);
}
return nth_ptr;
}
此代码已经过测试。
关于c - 如何多次使用 strchr() 查找第 n 次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46070363/