c语言strstr函数用法
C语言strstr函数用法
简介
strstr函数是C语言中用于在一个字符串中查子串的函数。它的原型如下:
char *strstr(const char *haystack, const char *needle);
该函数在字符串 haystack 中查 needle 第一次出现的位置,并返回指向该位置的指针。如果未到该子串,则返回空指针。
参数解析
haystack:要被搜索的字符串;
needle:要搜索的子串。
用法示例
以下是几个常见的使用示例,帮助你更好地理解strstr函数的用法。
示例1:查子串
#include <>
#include <>
int main() {
    char *str = "Hello World!";
    char *result;
    result = strstr(str, "World");
    if (result) {
        printf("到了子串!\n");
        printf("子串在str中的位置是:%s\n", result);
    } else {
        printf("未到子串!\n");
    }
    return 0;
}
输出结果为:
到了子串!
子串在str中的位置是:World!
示例2:未到子串
#include <>
#include <>
int main() {
    char *str = "Hello World!";
    char *result;
    result = strstr(str, "123");
    if (result) {
        printf("到了子串!\n");
        printf("子串在str中的位置是:%s\n", result);
    } else {
        printf("未到子串!\n");
    }
    return 0;
}
输出结果为:
未到子串!
示例3:查空字符串
#include <>
#include <>
int main() {
    char *str = "Hello World!";
    char *result;
    result = strstr(str, "");
    if (result) {
        printf("到了子串!\n");
        printf("子串在str中的位置是:%s\n", result);
    } else {
        printf("未到子串!\n");
    }
    return 0;
}
输出结果为:
到了子串!
子串在str中的位置是:Hello World!
小结
strstr函数是C语言中非常有用的字符串处理函数,可以方便地在一个字符串中查指定子串。通过本文的介绍,你应该对strstr函数的用法有了更加深入的了解。希望本文对你有所帮助!
示例4:查多次出现的子串
#include <>
#include <>
int main() {
    c语言char的用法char *str = "Hello World! Hello World!";
    char *result;
    result = strstr(str, "Hello");
    while (result != NULL) {
        printf("到了子串!\n");
        printf("子串在str中的位置是:%s\n", result);
        result = strstr(result + 1, "Hello");
    }
    return 0;
}
输出结果为:
到了子串!
子串在str中的位置是:Hello World! Hello World!
到了子串!
子串在str中的位置是:Hello World!