lets say i have 2 strings
假设我有2个字符串
char str_cp[50],str[50];
str[]="how are you"
and i want to put the second word ex "are" into another string named str_cp so if i use
我想把第二个单词ex“are”放入另一个名为str_cp的字符串中,如果我使用的话
printf("%s ,%s",str,str_cp);
will be like
会是这样的
how are you
are
how can i do that? (i tried strncpy function but it can copy only specific characters from beggining of the string ) is there any way to use a pointer which points at the 4th character of the string and use it in the strncpy function to copy the first 3 characters but the beggining point to be the 4th character ?
我怎样才能做到这一点? (我尝试过strncpy函数,但它只能复制字符串beggining中的特定字符)有没有办法使用指向字符串第4个字符的指针,并在strncpy函数中使用它来复制前3个字符但是开始点是第四个角色?
1 个解决方案
#1
18
I tried strncpy function but it can copy only specific characters from beggining of the string
我尝试了strncpy函数,但它只能复制字符串beggining中的特定字符
strcpy
family of functions will copy from the point that you tell it to copy. For example, to copy from the fifth character on, you can use
strcpy系列函数将从您告诉它复制的点复制。例如,要从第五个字符复制,您可以使用
strncpy(dest, &src[5], 3);
or
strncpy(dest, src+5, 3); // Same as above, using pointer arithmetic
Note that strncpy
will not null-terminate the string for you, unless you hit the end of the source string:
请注意,strncpy不会为您终止字符串,除非您点击源字符串的末尾:
No null-character is implicitly appended at the end of destination if source is longer than num (thus, in this case, destination may not be a null terminated C string).
如果source长于num,则在目标的末尾不会隐式附加空字符(因此,在这种情况下,destination可能不是空终止的C字符串)。
You need to null-terminate the result yourself:
您需要自己null终止结果:
strncpy(dest, &src[5], 3);
dest[3] = '\0';
#1
18
I tried strncpy function but it can copy only specific characters from beggining of the string
我尝试了strncpy函数,但它只能复制字符串beggining中的特定字符
strcpy
family of functions will copy from the point that you tell it to copy. For example, to copy from the fifth character on, you can use
strcpy系列函数将从您告诉它复制的点复制。例如,要从第五个字符复制,您可以使用
strncpy(dest, &src[5], 3);
or
strncpy(dest, src+5, 3); // Same as above, using pointer arithmetic
Note that strncpy
will not null-terminate the string for you, unless you hit the end of the source string:
请注意,strncpy不会为您终止字符串,除非您点击源字符串的末尾:
No null-character is implicitly appended at the end of destination if source is longer than num (thus, in this case, destination may not be a null terminated C string).
如果source长于num,则在目标的末尾不会隐式附加空字符(因此,在这种情况下,destination可能不是空终止的C字符串)。
You need to null-terminate the result yourself:
您需要自己null终止结果:
strncpy(dest, &src[5], 3);
dest[3] = '\0';