C语言 将特定字符从一个字符串复制到另一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14042047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
copy specific characters from a string to another string
提问by user1809300
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 函数,但它只能从字符串的开头复制特定字符)有什么方法可以使用指向字符串第 4 个字符的指针并在 strncpy 函数中使用它来复制前 3 个字符,但是起点是第 4 个字符?
回答by dasblinkenlight
I tried strncpy function but it can copy only specific characters from beggining of the string
我尝试了 strncpy 函数,但它只能从字符串的开头复制特定字符
strcpyfamily 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 strncpywill notnull-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 长,则不会在目标末尾隐式附加空字符(因此,在这种情况下,目标可能不是空终止的 C 字符串)。
You need to null-terminate the result yourself:
您需要自己对结果进行空终止:
strncpy(dest, &src[5], 3);
dest[3] = '##代码##';

