C语言简单实现substr函数

c语言中没有类似substr截取子串的函数,可以用strncpy,strncat实现

#include<cstdio>
#include<cstring>
using namespace std;
int main(){
    char a[20]="helloworld";
    char b[20]="";
    strncpy(b,a+2,5);
    puts(b);
        char c[20]="";
        strncat(c,&a[2],5);
        puts(c);  
    return 0;
}

注意:字符数组b和c,必须在使用前初始化,尤其是strncat数组,需要先查找dest(第一个参数)的长度,也就是尾0的位置,如果没有用空字符串清空,会把从第一个空字符前的字符当作dest中的字符。

猜你喜欢

转载自www.cnblogs.com/litifeng/p/12349039.html