2017-01-20 41 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  

} 
相關問題