例题11-8 字符定位 分数 15 作者 张泳 单位 浙大城市学院 输入一个字符串和一个字符,如果该字符在字符串中,就从该字符首次出现的位置开始输出字符串中的字符。本题要求编写函数match(s, ch),在字符串s中查找字符ch,如果找到,返回第一次找到的该字符在字符串中的位置(地址);否则,返回空指针NULL。 函数接口定义: char * match(char *s, char ch); 其中s是字符串首地址,ch是要查找的字符。 裁判测试程序样例: #include <stdio.h> char *match(char *s, char ch); /* 函数声明 */ int main(void ) { char ch, str[80], *p = NULL; scanf("%s", str); getchar(); ch = getchar(); if((p = match(str, ch)) != NULL) printf("%s\n", p); else printf("Not Found\n"); return 0; } /* 请在这里填写答案 */ 输入样例: program g 输出样例: gram
时间: 2023-12-24 09:06:02 浏览: 233
这道题需要遍历字符串,查找字符ch是否在字符串中,并返回第一次出现的位置。
函数实现如下:
```c
char* match(char* s, char ch) {
while (*s != '\0') { // 遍历字符串
if (*s == ch) { // 如果找到了字符ch
return s; // 返回该字符在字符串中的位置
}
s++; // 继续遍历字符串
}
return NULL; // 没有找到返回空指针
}
```
完整代码如下:
```c
#include <stdio.h>
char* match(char* s, char ch); // 函数声明
int main(void) {
char ch, str[80], *p = NULL;
scanf("%s", str);
getchar();
ch = getchar();
if ((p = match(str, ch)) != NULL)
printf("%s\n", p);
else
printf("Not Found\n");
return 0;
}
char* match(char* s, char ch) {
while (*s != '\0') { // 遍历字符串
if (*s == ch) { // 如果找到了字符ch
return s; // 返回该字符在字符串中的位置
}
s++; // 继续遍历字符串
}
return NULL; // 没有找到返回空指针
}
```