溫馨提示×

c語言怎么查找字符串指定字符串

小億
81
2024-09-26 00:52:00
欄目: 編程語言

在C語言中,查找字符串中的指定子字符串通常可以通過兩種方法實現(xiàn):使用strstr()函數(shù)和使用循環(huán)遍歷。

  1. 使用strstr()函數(shù): strstr()函數(shù)是C語言標(biāo)準(zhǔn)庫中的一個函數(shù),用于在一個字符串中查找另一個字符串首次出現(xiàn)的位置。其原型如下:
char *strstr(const char *str, const char *sub);

其中,str是要搜索的主字符串,sub是要查找的子字符串。如果找到了子字符串,strstr()函數(shù)返回子字符串在主字符串中首次出現(xiàn)的位置的指針;否則返回NULL。

示例代碼:

#include <stdio.h>
#include <string.h>

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;
}
  1. 使用循環(huán)遍歷: 如果你想從頭開始遍歷字符串以查找子字符串,可以使用for循環(huán)和strcmp()函數(shù)。下面是一個簡單的示例:
#include <stdio.h>
#include <string.h>

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()函數(shù)用于比較兩個字符串的前len_sub個字符。如果它們相等,那么子字符串就被找到了。

0