copy specific characters from a string to another string

前端 未结 1 1335
一向
一向 2021-02-06 01:36

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 nam

相关标签:
1条回答
  • 2021-02-06 02:29

    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';
    
    0 讨论(0)
提交回复
热议问题