从字符串复制特定字符另一个字符串 [英] copy specific characters from a string to another string

查看:116
本文介绍了从字符串复制特定字符另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有2字符串

 字符str_cp [50],海峡[50];
海峡[] =你好吗

和我想提出的第二个字恩是到名为str_cp另一个字符串,所以如果我使用

 的printf(%S%S,STR,str_cp);

会像

 你怎么样

我怎么能做到这一点?
(我试过函数strncpy功能,但它可以从字符串的beggining只复制特定的字符)
有没有办法使用它指向一个指针在字符串的第四个字符,并用它在函数strncpy功能的前3个字符,但beggining点复制是第四个字符?


解决方案

  

我试过了函数strncpy功能,但它可以从字符串的beggining只复制特定的字符


的strcpy 系列函数将复制从你告诉它复制的地步。例如,从第五个字符复制的,你可以使用

 函数strncpy(DEST,和放大器; SRC [5],3);

 函数strncpy(DEST,SRC + 5,3); //同上,使用指针运算

注意函数strncpy 将的的空终止字符串你,除非你打的源字符串的结尾:


  

没有空字符在目的到底隐含追加如果源长于NUM(因此,在这种情况下,目的地可能不是一个空结尾的C字符串)。


您需要用空字符结束,结果自己:

 函数strncpy(DEST,和放大器; SRC [5],3);
DEST [3] ='\\ 0';

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';

这篇关于从字符串复制特定字符另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆