编写函数求某字符在字符串中第一次出现的位置用c语言
时间: 2023-06-26 09:07:30 浏览: 81
可以使用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
```
c语言利用指针和函数求字符串1在字符串2中的位置
可以利用指针和函数来实现查找字符串1在字符串2中的位置。可以编写一个函数,接收两个字符串指针作为参数,并返回字符串1在字符串2中的位置。如果字符串1未在字符串2中出现,则返回-1。
示例代码如下:
```c
#include <stdio.h>
int str_find(char *str1, char *str2) {
int pos = -1;
char *p = str2;
while ((p = strchr(p, *str1)) != NULL) {
if (strncmp(p, str1, strlen(str1)) == 0) {
pos = p - str2;
break;
}
p++;
}
return pos;
}
int main() {
char str1[] = "hello";
char str2[] = "world, hello!";
int pos = str_find(str1, str2);
if (pos != -1) {
printf("字符串1在字符串2中的位置为:%d\n", pos);
} else {
printf("字符串1未在字符串2中出现!\n");
}
return 0;
}
```
在上面的代码中,`str_find()` 函数利用 `strchr()` 函数查找字符串2中字符为字符串1首字符的位置,然后用 `strncmp()` 函数比较该位置后面的字符是否与字符串1相同。如果相同,则返回该位置在字符串2中的偏移量,即字符串1在字符串2中的位置。如果找不到,则返回-1。