我试图想出一个办法,使这项工作:
//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;
}
此代码已经过测试。
最明显的(?)的方式当然是使用strchr()
的返回值作为新的字符串,加1到步骤过去已知的有,肯定发生后。
就像是:
const char * nth_strchr(const char *s, int c, int n)
{
for (;;)
{
if (n <= 0)
return NULL;
const char *h = strchr(s, c);
if(h == NULL)
return NULL;
if (--n == 0)
return h;
s = h + 1;
}
return NULL;
}
假设你是n
在串c
的s
th发生后,并没有n
th焦炭为您的评论说,那么这行
s = nth_ptr + 1;
在你的循环结束s
的c_count
的c
th occurence后会推动你s
指针字符。
请记住从strchr
检查返回值,如上面的评论中提到。
我认为代码可能是这样简单,使用计算(for
)循环与早期逃逸如果没有n
在字符串c
字符s
的出现:
const char *nth_strchr(const char *s, int c, int n)
{
const char *nth = s;
assert(c != '\0');
for (int i = 0; i < n; i++)
{
if ((nth = strchr(nth, c)) == 0)
break;
nth++;
}
return nth;
}
该break;
可以通过return 0;
或return NULL;
更换。条件可以== NULL
代替== 0
。我认为至少C99;如果你没有这种可这样做,那么你需要定义i
外循环。
有说法是极其迂腐。你不能去递增指针超出第一空没有的代码是如何被使用的详细知识,没有上下文,它使一个理智的选择。
其他答案有类似的净效应,但IMO的代码是不是写清楚(这就是为什么我这么多以后添加一个答案)。扩展循环的控制在三个线和在设置使用多任务使得它更难阅读比它需要的话。当使用一个计数的循环称为一个无限循环似乎混淆。
在代码中,你一直定位c
的第一次出现,你应该添加s = nth_ptr + 1;
如果nth_ptr
不NULL
,但你应该为n == 0
和/或c == '\0'
特殊情况。
下面是一个简单的版本:
const char *nth_strchr(const char *s, int c, int n) {
if (c == '\0' && n > 1) /* special case the null terminator */
return NULL;
if (n > 0) {
while ((s = strchr(s, c)) != NULL && --n > 0) {
s++;
}
}
return s;
}
//尝试这个程序
#include<stdio.h>
#include<string.h>
int main()
{
char *q,arr[]="This is strchr i program";
int i=0;
while((q=strchr(arr+i,'i'))!=NULL){
printf("%s\n",q);
i=(char *)q-(char *)arr;
i=i+1;
}
return 0;
}