strstr,strnstr函数详解

 strstr函数

strstr函数是C语言中的一个字符串函数,用于在一个字符串中查找另一个字符串的出现位置。

它的函数原型如下:

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

在这个函数中,haystack表示被搜索的字符串,needle表示要查找的子字符串。函数的返回值是一个指针,指向第一次出现needle的位置,如果没有找到,返回NULL。

例如,我们可以使用strstr函数来查找一个字符串中是否包含另一个字符串:

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

int main() {
  char haystack[] = "Hello, world!";
  char needle[] = "world";

  char *result = strstr(haystack, needle);

  if (result != NULL) {
    printf("'%s' is found in '%s' at position %ld.\n", needle, haystack, result - haystack);
  } else {
    printf("'%s' is not found in '%s'.\n", needle, haystack);
  }

  return 0;
}

上述代码输出为:

'world' is found in 'Hello, world!' at position 7.

需要注意的是,strstr函数是区分大小写的,如果要进行大小写不敏感的查找,可以使用其他函数,例如strcasestr。

使用示例

查找子字符串成功后,用strncpy修改内存块内容。

#include <stdio.h>
#include <string.h> 
#include<assert.h>
 
int main()
{
    char str[] = "This is a simple string hello world!";
    char* pch;
    pch = strstr(str, "string");
    if (pch != NULL)
    {
        printf("%s\n",str);
        printf("%s\n",pch);
        strncpy(pch, "sifang",6);
    }
    printf("%s\n",str);
    printf("%s\n",pch);
    return 0;
}


输出结果:

 由输出的结果可知,pch的内容为str的子字符串,指向

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值