0

问题就像标题一样,我已经写了一个代码来实现这个功能。代码如下,但是语句:*(str+length_copy-1+tail_space_num) = *(str+length_copy-1); 导致错误。你能帮我一把吗?任何形式的答案都会有所帮助!

#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");    
}
4

1 回答 1

2

Yourstr是一个初始化为字符串文字的指针,它是只读的。相反,您应该将可写数组传递char给函数。

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

我提出的解决方案创建str一个数组,而不是使用 NUL 终止字符串的内容以及"Mr John Smith"NUL 字节后面的一些填充空格字符(并且填充空格后面跟着另一个 NUL)。

于 2013-05-16T05:47:54.647 回答