c语言查找字符是否存在
时间: 2023-10-26 08:21:34 浏览: 41
你可以使用C语言中的字符串库函数`strchr()`来查找一个字符是否存在于字符串中。该函数的原型为:
```c
char* strchr(const char* str, int c);
```
其中,`str`是需要查找的字符串,`c`是需要查找的字符。函数返回一个指向`str`中第一次出现`c`的位置的指针,如果`c`不存在于`str`中,则返回NULL。以下是一个例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello";
char c = 'e';
char* ptr = strchr(str, c);
if (ptr != NULL) {
printf("%c exists in %s at position %ld.\n", c, str, ptr - str);
} else {
printf("%c does not exist in %s.\n", c, str);
}
return 0;
}
```
该程序会输出:`e exists in hello at position 1.`
相关问题
c语言查找字符串子串
可以使用C语言中的strstr函数来查找字符串子串。该函数的原型为:
```c
char *strstr(const char *str1, const char *str2);
```
其中,str1为要查找的字符串,str2为要查找的子串。函数返回值为指向第一次出现子串的指针,如果没有找到则返回NULL。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello world";
char str2[] = "world";
char *ptr = strstr(str1, str2);
if (ptr != NULL) {
printf("子串在字符串中的位置:%d\n", ptr - str1);
} else {
printf("未找到子串\n");
}
return 0;
}
```
输出结果为:
```
子串在字符串中的位置:6
```
C语言查找字符数组中的字符
要在C语言中查找字符数组中的字符,可以使用字符串库中的函数或者自己编写循环遍历数组的代码实现。
使用字符串库函数:
1. 使用 strchr 函数,该函数返回字符串中第一次出现指定字符的位置,如果未找到该字符,则返回 NULL。
```c
char str[] = "hello world";
char c = 'o';
char *pos = strchr(str, c);
if (pos != NULL) {
printf("Found %c at position %ld\n", c, pos - str);
} else {
printf("Character not found\n");
}
```
2. 使用 strstr 函数,该函数返回字符串中第一次出现指定子字符串的位置,如果未找到该子字符串,则返回 NULL。
```c
char str[] = "hello world";
char sub[] = "world";
char *pos = strstr(str, sub);
if (pos != NULL) {
printf("Found '%s' at position %ld\n", sub, pos - str);
} else {
printf("Substring not found\n");
}
```
自己编写代码:
```c
char str[] = "hello world";
char c = 'o';
int pos = -1;
for (int i = 0; i < strlen(str); i++) {
if (str[i] == c) {
pos = i;
break;
}
}
if (pos != -1) {
printf("Found %c at position %d\n", c, pos);
} else {
printf("Character not found\n");
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)