C语言一个字符串在另一个字符串中出现的位置
时间: 2023-09-03 19:12:52 浏览: 89
你可以使用C语言中的strstr函数来查找一个字符串在另一个字符串中出现的位置。strstr函数返回第一次出现子字符串的地址,如果没有找到则返回NULL。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, world!";
char str2[] = "world";
char *ptr;
ptr = strstr(str1, str2);
if (ptr != NULL) {
printf("'%s' is found in '%s' at position %d.\n", str2, str1, ptr - str1);
} else {
printf("'%s' is not found in '%s'.\n", str2, str1);
}
return 0;
}
```
运行结果是:
```
'world' is found in 'Hello, world!' at position 7.
```
相关问题
C语言在一个字符串中删除另一个字符串
可以使用C语言的字符串操作函数来实现删除一个字符串中的另一个字符串。
以下是一个示例代码:
```
#include <stdio.h>
#include <string.h>
void removeSubstring(char *s, const char *t) {
int i, j, k, n = strlen(t);
for (i = j = 0; s[i] != '\0'; i++) {
if (strncmp(&s[i], t, n) == 0) {
i += n;
} else {
s[j++] = s[i];
}
}
s[j] = '\0';
}
int main() {
char s[100], t[100];
printf("Enter a string: ");
fgets(s, 100, stdin);
printf("Enter a substring to remove: ");
fgets(t, 100, stdin);
removeSubstring(s, t);
printf("Result: %s\n", s);
return 0;
}
```
在这个例子中,`removeSubstring` 函数接受两个字符串 `s` 和 `t` 作为参数。它在 `s` 中查找并删除所有出现的 `t` 子字符串。`strncmp` 函数用于比较字符串,`i` 和 `j` 分别表示正在读取的字符位置和写入的字符位置。如果找到了 `t` 子字符串,则将 `i` 移动到子字符串的末尾,从而跳过它。
在主函数中,用户被提示输入一个字符串和要删除的子字符串。然后调用 `removeSubstring` 函数并打印结果。
注意:在这个例子中,我们假设输入的字符串不包含任何换行符。如果输入字符串可能包含换行符,则需要进行额外的处理。
c语言查询指定字符在一个字符串中最后出现的位置
可以使用C语言的库函数`strrchr`来查询指定字符在一个字符串中最后出现的位置。`strrchr`函数的用法如下:
```c
char *strrchr(const char *str, int c);
```
其中,`str`为要查找的字符串,`c`为要查找的字符。该函数返回指向字符串中指定字符最后出现位置的指针,如果未找到该字符则返回NULL。
以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char *ptr = strrchr(str, 'l');
if (ptr != NULL) {
printf("最后出现位置的指针为:%p\n", ptr);
printf("最后出现位置的下标为:%ld\n", ptr - str);
}
return 0;
}
```
输出结果为:
```
最后出现位置的指针为:0x7fff5fbff7
最后出现位置的下标为:9
```
其中,最后出现位置的指针为0x7fff5fbff7,最后出现位置的下标为9,表示字符'l'在字符串中最后出现的位置为下标为9。