2017-07-28 56 views
0

是那裏與%%取代的%所有出現在下面的字符串的實用方法用%%?替換所有%的出現,需要一個函數嗎?

char * str = "%s %s %s"; 

printf("%s",str); 

所以結果是:

%%s %%s %%s 

,或者必須我使用其中掃描每個字在一個功能該字符串直到找到%,然後用%%替換它?

+4

有一個在標準庫中沒有這樣的功能,所以,是的,你必須寫你自己的。 –

+2

首先,由於字符串文字不能被改變,所以有必要分配一個允許數組或者分配另一個數組。 – BLUEPIXY

+2

可能重複[什麼是替換C中的字符串?](https://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c) – phd

回答

1

您應該明白,不能在同一個str中進行替換,因爲增加字符數將需要更多內存。因此在更換替換次數之前必須計算在內。

以下函數允許將單個字符替換爲字符串(字符集)。

char *replace(const char *s, char ch, const char *repl) { 

    // counting the number of future replacements 
    int count = 0; 
    const char *t; 
    for(t=s; *t; t++) 
    { 
     count += (*t == ch); 
    } 

    // allocation the memory for resulting string 
    size_t rlen = strlen(repl); 
    char *res = malloc(strlen(s) + (rlen-1)*count + 1); 
    if(!res) 
    { 
     return 0; 
    } 
    char *ptr = res; 

    // making new string with replacements 
    for(t=s; *t; t++) { 
     if(*t == ch) { 
      memcpy(ptr, repl, rlen); // past sub-string 
      ptr += rlen; // and shift pointer 
     } else { 
      *ptr++ = *t; // just copy the next character 
     } 
    } 
    *ptr = 0; 

    // providing the result (memory allocated in this function 
    // should be released outside this function with free(void*)) 
    return res; 
} 

爲特定的任務,此功能可以作爲

char * str = "%s %s %s"; 
char * newstr = replace(str, '%', "%%"); 
if(newstr) 
    printf("%s",newstr); 
else 
    printf ("Problems with making string!\n"); 

注意的是,新的字符串存儲在堆(動態內存對於分配到初始字符串和更換的數量的大小),所以當不再需要newstr時,並且在程序指出newstr指針的範圍之前,應該重新分配存儲器。

試想在一個地方,

if(newstr) 
{ 
    free(newstr); 
    newstr = 0; 
} 
+0

潛在的內存泄漏*檢測到* :) –

+3

您應該在'return'語句之前添加'* ptr ='\ 0';'。 –

+0

@squeamishossifrage是的!更新 – VolAnd

相關問題