函数原型:
#include <string.h>
char *strstr(const char *haystack, const char *needle);功能:strstr 函数在给定的目标字符串(haystack)中查找子字符串(needle)首次出现的位置,并返回子字符串在目标字符串中的起始地址。如果子字符串未在目标字符串中找到,则返回 NULL。
参数:
haystack:指向要搜索的字符串(目标字符串)的指针。needle:指向要查找的子字符串的指针。
返回值:
如果在
haystack中找到了needle,则返回指向needle在haystack中起始位置的指针。如果在
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将子字符串的所有字符设置为 *,从而达到修改子字符串的效果。
      
      
      
评论区