C/C++用strncpy()与strstr()分割与匹配查找字符串

一、strncpy()

char * strncpy ( char * destination, const char * source, size_t num );

strncpy() 在 <string.h>头文件中(C++中为<cstring>),拷贝原字符串S中长度为num的部分至目标字符串D中。

#include <stdio.h>
#include <string.h>
 
int main() {
    char source[] = "hello world";
    char str1[20];
    char str2[20];
    // 拷贝source中从0到5的字符串
    strncpy(str1, source, 6); // 0~5: 长度为6
    puts(str1);
    // 运行后结果为 hello
     
    // 拷贝source中从1到5的字符串
    strncpy(str2, source+1, 5); // 1~5: 长度为5
    puts(str2);
    // 运行后结果为 ello
     
    // 原字符串不变
    puts(source);
    // 运行后结果为 hello world
    return 0;
}

分割字符串中,原字符串是不会改变的,同时分割的起点是通过指针控制的,而结束点则是通过长度间接决定的,使用时需要注意。

二、strstr()

const char * strstr ( const char * str1, const char * str2 );
      char * strstr (       char * str1, const char * str2 );

其中str1是原字符串,str2是带匹配的字符串,返回第一次str2出现的位置(指针)

#include <stdio.h>
#include <string.h>
 
int main() {
    char source[] = "hello world hello world";
    char str1[] = "hello";
    char *str2;
     
    // 查找第一个hello出现的位置
    printf("%d\n", strstr(source, str1) - source);
    // 运行后结果为0
     
         
    // 查找第一个world出现的位置
    str2 = strstr(source, "world");
    printf("%d\n", str2 - source);
    // 运行后结果为6
     
         
    // 查找第二个world出现的位置
    printf("%d\n", strstr(source + (str2 - source) + 1, "world") - source);
    // 运行后结果为18
     
    return 0;
}

因为返回的是指针,如果需要计算位置的话,可以通过指针相减的方式,进行计算得到。

因为返回的时第一次找到的位置,所以要想找到第N次(N > 1)出现的位置,就要从第N-1次出现的位置+1处开始寻找。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值