lets say i have 2 strings
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
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 ?
I tried strncpy function but it can copy only specific characters from beggining of the string
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
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:
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).
You need to null-terminate the result yourself:
strncpy(dest, &src[5], 3);
dest[3] = '\0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With