Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy specific characters from a string to another string

Tags:

c

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 ?

like image 528
user1809300 Avatar asked Dec 26 '12 14:12

user1809300


1 Answers

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';
like image 88
Sergey Kalinichenko Avatar answered Sep 27 '22 18:09

Sergey Kalinichenko