侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

C库函数-strstr

zze
zze
2024-03-25 / 0 评论 / 0 点赞 / 13 阅读 / 4162 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

函数原型:

#include <string.h>

char *strstr(const char *haystack, const char *needle);

功能:strstr 函数在给定的目标字符串(haystack)中查找子字符串(needle)首次出现的位置,并返回子字符串在目标字符串中的起始地址。如果子字符串未在目标字符串中找到,则返回 NULL

参数:

  • haystack:指向要搜索的字符串(目标字符串)的指针。

  • needle:指向要查找的子字符串的指针。

返回值:

  • 如果在 haystack 中找到了 needle,则返回指向 needlehaystack 中起始位置的指针。

  • 如果在 haystack 中未找到 needle,则返回 NULL

示例:

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

int main() {
    char str[] = "Hello, this is a sample string.";
    char target[] = "sample";

    char *found = strstr(str, target);

    if (found != NULL) {
        printf("Substring '%s' found at position %td\n", target, found - str);
    } else {
        printf("Substring '%s' not found in the given string.\n", target);
    }

    return 0;
}

在上述示例中,我们正在搜索字符串 "Hello, this is a sample string." 中的子字符串 "sample"。如果找到子字符串,则输出子字符串在目标字符串中的起始位置索引。如果未找到子字符串,则输出提示信息。

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

int main() {
    char originalStr[100] = "Hello, this is a sample string.";
    char targetStr[] = "sample";

    // 查找子字符串在原始字符串中的位置
    char *found = strstr(originalStr, targetStr);
    
    if (found != NULL) {
        // 使用 memset 清除子字符串及其之后的部分
        memset(found, '*', strlen(targetStr));
        printf("Original string: %s\n", originalStr);
    } else {
        printf("Substring '%s' not found in the given string.\n", targetStr);
    }

    return 0;
}

在这个示例中,我们首先使用strstr找到子字符串"sample"在原始字符串中的位置。一旦找到,使用memset将子字符串的所有字符设置为 *,从而达到修改子字符串的效果。

0

评论区