2011-09-04 42 views
-1

如果他們在toBlank發現下面的函數應替換s發現空格字符:Ç - 比較字符串

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

/* function blank replaces all characters in the parameter string s 
* that are present in the parameter string toBlank with space characters. 
* for example, if s were the string "abcdef" and toBlank the string 
* "bde", then after calling this function, s would be "a c f" */ 
void blank(char *s, const char *toBlank){ 
    int i=0, j=0; 
    while (s[i] != '\0'){ 
     if (s[i] == toBlank[j]){ 
      s[i] = ' '; 
     }else{ 
      j++; 
     } 
     i++; 

    } 
    printf("%s", s); 
} 

int main(void){ 
    blank("abcdef", "bde"); 
} 

的問題是,s永遠不會被修改。有人可以解釋發生了什麼嗎?

+3

請介紹更多的細節「不工作」(編輯你的問題),並選擇一個更好的標題你的進步 - 這是關於在一個字符串替換的東西,而不是比較字符串。 – Mat

回答

6

您正在傳遞一個字符串文字(實際上是const)作爲您的第一個參數,然後您嘗試在函數中對其進行修改。

而是執行此操作:

int main(void) 
{ 
    char s[] = "abcdef"; 

    blank(s, "bde"); 

    return 0; 
} 
3

我認爲你需要遍歷在toBlank的字符。

void blank(char *s, const char *toBlank) 
{ 
    int i=0, j; 
    while (s[i] != '\0') 
    { 
     j = 0; 
     while(toBlank[j] != '\0') 
     { 
      if (s[i] == toBlank[j]) 
      { 
       s[i] = ' '; 
       break; 
      } 
      else 
      { 
       ++j; 
      } 
     } 
     ++i; 
    } 
    printf("%s", s); 
} 
+0

您還必須爲每個i重置j。 – quasiverse

+0

@quasiverse好的。我相應地改變了。 – tgoodhart

+0

+1:您對「錯誤處理的循環條件」的診斷是準確的。內循環可以簡化爲:for(int j = 0; toBlank [j]!='\ 0'; j ++){if(s [i] == toBlank [j]){s [i] =' 「;打破; }}'這是最多8行,而你的答案是13。它也可以改爲:'if(strchr(toBlank,s [i])!= 0)s [i] ='';'爲了更有戲劇性的節省。事實上,函數的整體可以是:for(int i = 0; s [i]!=''0'; i ++){if(strchr(toBlank,s [i])!= 0)s [我] =''; } printf(「%s \ n」,s);'總共6行。 –

0

難道你不想讓j ++裏面的if和not else嗎? 我想,當你發現炭

1
/* there are stdlib functions for these kind of things */ 

#include <stdlib.h> 
void blank(char *str, char * wits) 
{ 
size_t pos,len; 

for (pos=len=0; str[pos]; pos += len) { 
    len = strspn(str+pos, wits); 
    if (len) memset(str+pos, ' ', len); 
    else len = strcspn(str+pos, wits); 
    } 
}