2013-05-16 38 views
0

問題在於標題,並且我寫了一個代碼來實現此功能。代碼如下,但是句子:*(str + length_copy-1 + tail_space_num)= *(str + length_copy-1);導致錯誤。 你能幫我一下嗎?任何形式的答案都會有幫助!用'%20'替換字符串中的所有空格。假設字符串在字符串的末尾有足夠空間容納附加字符

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

void replaceSpace(char* str){ 
if(str == NULL){ 
    printf("The parameter is null pointer\n"); 
}else if(strlen(str) == 0){ 
    printf("The parameter you parse into is a empty string\n"); 
}else{ 
    int length,length_copy,space_num,tail_space_num; 
    length=length_copy=strlen(str); 
    space_num=tail_space_num =0; 
    while(*(str + length -1) == ' '){//' ' is char, but " " is string 
     tail_space_num++; 
     length--; 
    } 

    length_copy = length; 

    while(length-1>=0){ 
     if(*(str+length-1) == ' ') 
      space_num++; 
     length--; 
    } 
    printf("%d\n",length_copy); 
    printf("%d\n",tail_space_num); 
    printf("%d\n",space_num); 
    if(space_num * 2 != tail_space_num){ 
     printf("In the tail of the string, there is not enough space!\n"); 
    }else{ 
     while((length_copy-1)>=0){ 
      if(*(str+length_copy-1)!=' '){ 
       *(str+length_copy-1+tail_space_num) = *(str+length_copy-1); 
      }else{ 
       *(str+length_copy-1+tail_space_num) = '0'; 
       *(str+length_copy-2+tail_space_num) = '2'; 
       *(str+length_copy-3+tail_space_num) = '%'; 
       tail_space_num = tail_space_num -2; 
      } 
      length_copy --; 
     } 
    } 
} 
} 

main(){ 
char* str = "Mr John Smith "; 
printf("The original string is: %s\n", str); 
printf("the length of string is: %d\n", strlen(str)); 
replaceSpace(str); 
printf("The replaced string is: %s\n", str); 
system("pause");  
} 
+0

什麼是錯誤信息? – Patashu

+0

我認爲有一種情況是轉換區域不夠用。 – BLUEPIXY

回答

2

str是一個指針,它被初始化爲一個字符串,它是隻讀的。您應該將一個可寫數組char傳遞給函數。

char str[] = "Mr John Smith\0  "; 

我提出的解決方案使得str陣列而不是與NUL的內容初始化結束的字符串"Mr John Smith",並按照NUL字節(和填充空間後跟另一個NUL)一些填充空格字符。

+0

您可能想指出,您的代碼**將字符串文字複製到數組中(我假設發生了什麼),而不是指針方法,它只會使'str'指向* *字符串文字。 – Dukeling

+0

是的,問題是設置爲固定的字符串是隻讀的。除非我malloc一個內存並從鍵盤讀取,否則字符串(char *)不能被重寫。感謝你的幫助。 –

相關問題