nas*_*uto 1 c string pointers strchr
好的,我的教授给我布置了一个作业。这里是:
编写一个名为 strchr406 的函数。它传递 2 个参数:一个字符串和一个 char 以下是该函数的原型: char *strchr406(char str[], char ch); 该函数应返回指向 str 中 ch 的第一个实例的指针。例如:
char s[ ] = "abcbc";
strchr406(s, 'b'); // returns s + 1 (i.e., a pointer to the first 'b' in s)
strchr406(s, 'c'); // returns s + 2
strchr406(s, 'd'); // returns 0
Run Code Online (Sandbox Code Playgroud)
他要求我们使用指针编写我们自己的 strchr 版本。我在网上查找资源,但没有一个符合他要求我们做的事情。我正在和一群其他学生一起工作,但我们没有人能弄清楚这一点。
我们如何返回“s + 1”?
到目前为止,我有这个:(如果更容易的话,我也把它放在网上:https: //repl.it/FVK8)
#include <stdio.h>
#include "string_problems.h"
int main() {
char s[ ] = "abcbc";
strchr406(s, 'b'); // returns s + 1 (i.e., a pointer to the first 'b' in s)
strchr406(s, 'c'); // returns s + 2
strchr406(s, 'd'); // returns 0
printf("this should return %s\n", strchr406(s, 'c'));
return 0;
}
char *strchr406(char str[], char ch) {
char *p = str;
int index = 0;
while (*str != ch) {
++str;
++index;
}
if (*str == ch) {
return p + index;
} else {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到奇怪的输出。任何帮助表示赞赏。
从手册中:
char *strchr(const char *s, int c);--> 第二个参数是一个 intchar *strchr42(char *str, int ch)
{
for (;; str++) {
if (*str == ch) return str;
if (!*str) return NULL;
}
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
甚至更短:
char *strchr42a(char *str, int ch)
{
do {
if (*str == ch) return str;
} while (*str++) ;
return NULL;
}
Run Code Online (Sandbox Code Playgroud)