2017-01-20 47 views
0

如果我有字符串复制从具体指数动态地使用C

char str_cp[50],str[50], str_other[50], str_type[50]; 
strcpy(str,"how are you : i am fine"); 
strcpy(str_other, "who are you : may be robot or human being"); 
strcpy(str_type,"type : worker/manager "); 

所以如何编写...复制从一个字符串“:”结束行的?当我不知道 结束指数。

+1

一个好的开始可能是[找到分隔字符](http://en.cppreference.com/w/c/string/byte/strchr)。 –

+0

“结束指数”是什么意思?你不是一直复制到字符串的末尾吗? – dasblinkenlight

+0

结束索引意味着...行的最后一个字符。 –

回答

2

在C,从一个特定的字符复制到字符串的结尾,可以用strcpy来完成,假设你有一个足够大的缓冲区。您只需将指针传递给您想要保留的首字符。

指针可以strchr发现,像这样:

const char *tail = strchr(str, ':') + 1; // skip ':' itself. Add 2 to skip ' ' too 

如果打印tail,你会得到字符串的其余部分的内容:如果你需要一个

​​3210

复制,制作strcpy

size_t len = strlen(tail)+1; 
char *copy = malloc(len); 
strcpy(copy, tail); 
2

做出不同的阵列大小为50,然后只是复制

char source[150]; // supoose your sorce array 
char dest[150]; // suppose your destination 
int i =0,Flag =0,j=0; 

for(char c = source[i];c != '\0';i++) 
{ if(c == ':') 
     Flag = 1; // coz we have to start copying from here 

    if(Flag == 1) 
     dest[j++]=c; //copying the elements 
    } 
+1

我们可以编辑它来省略Flag,就像if(c ==':'|| strlen(dest)> 0){dest [j ++] = c; } –

+0

是的,它可以工作,但性能会降低@vijaymishra upvote如果你觉得这有帮助谢谢 –

+0

Bcoz这是一个短而没有循环。我甚至给你投票。谢谢 –

0
typedef struct string String; //do we suppose you wrote a string buffer 
// to avoid mallloc and reallock 
char * d_prs(String * buf; char * to_parse) 
{ 
    reset_st(buf);// do you suppose you have a macro to reset the buffer 
    while(*to_parse) 
     if(*to_parse++==':') break; 
    if(!*to_parse)return NULL; //if null the str, does not contain ':' 
    concat_s(buf,to_parse); //the pointer is right initalized...justcpy 
    return str_toCstring(buf);//a macro to get the data of the buffer  

} 
相关问题