编写程序,从键盘输入一个字符ch,在字符串中查找是否存在有该字符,若存在,则给出该字符在字符串中第1次出现的位置。 要求设计函数char * search(char *str,char c),其功能为:在str所指的字符串中,查找是否有字符变量c的字符,如果有,返回字符串中相同字符的地址,如果没有则返回null
时间: 2023-06-05 09:47:25 浏览: 189
此题意为:编写程序,从键盘输入一个字符ch,在字符串中查找是否存在该字符,若存在,则给出该字符在字符串中第1次出现的位置。要求设计函数char * search(char *str,char c),其功能为:在str所指的字符串中,查找是否有字符变量c的字符,如果有,则返回字符串中相同字符的地址,如果没有,则返回NULL。
相关问题
编写程序,从键盘输入一个字符ch,在字符串string中查找是否存在有该字符,若存在,给出该字符在字符串中第1次出现的位置。(采用函数调用,指针作为参数)
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int find_char(char ch, const char* string) {
int pos = 0;
while (*string != '\0') {
if (*string == ch) {
return pos;
}
++string;
++pos;
}
return -1; // 找不到该字符
}
int main() {
char ch;
cout << "请输入一个字符:";
cin >> ch;
char string[100];
cout << "请输入一个字符串:";
cin >> string;
int pos = find_char(ch, string);
if (pos == -1) {
cout << "没有找到该字符" << endl;
} else {
cout << "该字符在字符串中第一次出现的位置为:" << pos << endl;
}
return 0;
}
```
在这个程序中,我们使用 `find_char` 函数来查找字符 `ch` 在字符串 `string` 中第一次出现的位置。该函数通过指针 `string` 遍历整个字符串,一旦找到字符 `ch`,就返回当前位置。如果遍历完整个字符串都没有找到该字符,就返回 -1。
在主函数中,我们先从键盘输入一个字符 `ch` 和一个字符串 `string`,然后调用 `find_char` 函数来查找字符 `ch` 在字符串 `string` 中第一次出现的位置。最后根据返回值输出结果。
用c语言编写程序,从键盘输入一个字符 ch,在字符串string 中查找是否存在有该字符,若存在,给出该字符在字符串中第1次出现的位置。(采用函数调用,指针作为参数)
可以使用以下的程序来实现:
```c
#include <stdio.h>
#include <string.h>
int find_char(char *str, char ch);
int main(void) {
char string[100], ch;
printf("请输入字符串:");
scanf("%s", string);
printf("请输入要查找的字符:");
scanf(" %c", &ch);
int pos = find_char(string, ch);
if (pos == -1) {
printf("字符串中不存在该字符。\n");
} else {
printf("该字符在字符串中第一次出现的位置是:%d\n", pos);
}
return 0;
}
int find_char(char *str, char ch) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == ch) {
return i;
}
}
return -1;
}
```
在程序中,我们定义了一个 `find_char` 函数,该函数接收一个字符串和一个字符作为参数,用于在字符串中查找是否存在有该字符。如果存在,则返回该字符在字符串中第一次出现的位置(从0开始),如果不存在,则返回-1。
在 `main` 函数中,我们先从键盘输入一个字符串和一个字符,然后调用 `find_char` 函数来查找该字符在字符串中的位置。最后输出结果即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)