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

最近做题遇到分割与匹配字符串的题目(hdu5311),看来别人的代码,才知道有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
", strstr(source, str1) - source);
    // 运行后结果为0
    
        
    // 查找第一个world出现的位置
    str2 = strstr(source, "world");
    printf("%d
", str2 - source);
    // 运行后结果为6
    
        
    // 查找第二个world出现的位置
    printf("%d
", strstr(source + (str2 - source) + 1, "world") - source);
    // 运行后结果为18
    
    return 0;
}

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

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

原文地址:https://www.cnblogs.com/Emerald/p/4702785.html