阅读量:86
在C语言中,查找字符串中的指定子字符串通常可以通过两种方法实现:使用strstr()函数和使用循环遍历。
- 使用
strstr()函数:strstr()函数是C语言标准库中的一个函数,用于在一个字符串中查找另一个字符串首次出现的位置。其原型如下:
char *strstr(const char *str, const char *sub);
其中,str是要搜索的主字符串,sub是要查找的子字符串。如果找到了子字符串,strstr()函数返回子字符串在主字符串中首次出现的位置的指针;否则返回NULL。
示例代码:
#include
#include
int main() {
const char *str = "Hello, welcome to the world of C language!";
const char *sub = "C language";
char *result = strstr(str, sub);
if (result != NULL) {
printf("Found '%s' in the string.\n", sub);
printf("The position is: %lu\n", (unsigned long)result - (unsigned long)str);
} else {
printf("The substring '%s' was not found.\n", sub);
}
return 0;
}
- 使用循环遍历:
如果你想从头开始遍历字符串以查找子字符串,可以使用
for循环和strcmp()函数。下面是一个简单的示例:
#include
#include
int main() {
const char *str = "Hello, welcome to the world of C language!";
const char *sub = "C language";
size_t len_str = strlen(str);
size_t len_sub = strlen(sub);
int found = 0;
for (size_t i = 0; i <= len_str - len_sub; i++) {
if (strncmp(str + i, sub, len_sub) == 0) {
found = 1;
printf("Found '%s' in the string.\n", sub);
printf("The position is: %lu\n", (unsigned long)i);
break;
}
}
if (!found) {
printf("The substring '%s' was not found.\n", sub);
}
return 0;
}
在这个例子中,strncmp()函数用于比较两个字符串的前len_sub个字符。如果它们相等,那么子字符串就被找到了。