让我说我有2个字符串
char str_cp[50],str[50];
str[]="how are you"
Run Code Online (Sandbox Code Playgroud)
我想将第二个单词ex"are"放入另一个名为str_cp的字符串中,如果我使用的话
printf("%s ,%s",str,str_cp);
Run Code Online (Sandbox Code Playgroud)
会是这样的
how are you
are
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?(我尝试过strncpy函数但它只能复制字符串beggining中的特定字符)有没有办法使用指向字符串第4个字符的指针并在strncpy函数中使用它来复制前3个字符但是开始点是第四个角色?
das*_*ght 21
我尝试了strncpy函数,但它只能复制字符串beggining中的特定字符
strcpy函数族将从您告诉它复制的点复制.例如,要从第五个字符复制,您可以使用
strncpy(dest, &src[5], 3);
Run Code Online (Sandbox Code Playgroud)
要么
strncpy(dest, src+5, 3); // Same as above, using pointer arithmetic
Run Code Online (Sandbox Code Playgroud)
请注意,strncpy将不空终止字符串你,除非你打的源字符串的结尾:
如果source长于num,则在目标的末尾不会隐式附加空字符(因此,在这种情况下,destination可能不是空终止的C字符串).
您需要自己null终止结果:
strncpy(dest, &src[5], 3);
dest[3] = '\0';
Run Code Online (Sandbox Code Playgroud)