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中的字符。