C语言:求字符串s中第一次出现字符c的位置,如不存在返回-1,用指针完成
时间: 2024-05-04 13:16:44 浏览: 14
可以使用指针遍历字符串s,找到第一次出现字符c的位置。如果找到了,返回该字符在字符串中的索引值;如果没有找到,返回-1。
以下是代码示例:
```c
#include <stdio.h>
int find_char(const char* s, char c) {
const char* p = s;
int index = 0;
while (*p != '\0') {
if (*p == c) {
return index;
}
p++;
index++;
}
return -1;
}
int main() {
char s[] = "Hello, world!";
char c = 'o';
int index = find_char(s, c);
if (index != -1) {
printf("The first occurrence of %c is at index %d.\n", c, index);
} else {
printf("%c does not occur in %s.\n", c, s);
}
return 0;
}
```
运行结果:
```
The first occurrence of o is at index 4.
```
相关问题
编写函数求某字符在字符串中第一次出现的位置用c语言
可以使用C语言的标准库函数`strchr()`来实现。`strchr()`函数的原型为:
```c
char *strchr(const char *s, int c);
```
该函数在字符串`s`中查找字符`c`第一次出现的位置,并返回该位置的指针。如果未找到该字符,则返回`NULL`指针。
以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char ch = 'o';
char *pos = strchr(str, ch);
if (pos != NULL) {
printf("'%c' first appears at position %d\n", ch, pos - str);
} else {
printf("'%c' not found in string\n", ch);
}
return 0;
}
```
输出结果为:
```
'o' first appears at position 4
```
注意,`pos - str`表示`pos`指针相对于字符串起始地址`str`的偏移量,即字符在字符串中的位置。
c语言 求指定字符在字符串中最后一次出现的位置 fun
可以使用C语言的标准库函数`strrchr`来实现求指定字符在字符串中最后一次出现的位置。`strrchr`函数返回指向最后一个指定字符的指针。如果找不到该字符,则返回空指针。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char ch = 'o';
char *p = strrchr(str, ch); // 查找字符ch在字符串str中最后一次出现的位置
if (p == NULL) {
printf("字符%c在字符串中未出现\n", ch);
} else {
printf("字符%c在字符串中最后一次出现的位置是:%ld\n", ch, p - str);
}
return 0;
}
```
输出结果为:
```
字符o在字符串中最后一次出现的位置是:7
```
相关推荐
![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_column_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)