犯了一个错误,char× 在C++ 中会 直接定义一块内存,不可访问内存以外的地方,所有用到该常量字符串的地方都是一个地址, 所以用str[p2]时,会报错,SIGSEGV (Segmentation fault),就是说内存访问错误, 所以应该用char [],只指定 字符串首地址,便可以访问了 #include <iostream> using namespace std; //替换空格 //首先询问,是在原字符串上修改,还是新创字符串修改 //o(n平方) 从前面,每找到一个空格,就增加两个,替换 //0(n):从后面 // 首先统计空格个数,计算出替换后最终的个数 // 然后两个指针,一个指向新字符串的尾, // 一个指向旧字符串的尾 // 从后面开始遍历,当旧指针 遇到空格, -- // 新指针用%20替换 bool replaceStr(char str[], int length) { int count=0; int i=0; //统计空格个数 while(str[i]!='\0') { if(str[i] ==' ') { count++; } i++; } int old_length = length; //计算新字符串长度 int new_length = 2*count+old_length; int p2=new_length; int p1 = old_length; //从后面遍历替换空格 for(;p2>=0&&p1>0;p2--,p1--) { // 不是空格时 if(str[p1]!=' ') { str[p2] = str[p1]; } //是空格时,替换 else { str[p2] = '0'; str[--p2] = '2'; str[--p2] = '%'; } } return true; } int main() { char str[] = "We are happy."; replaceStr(str,14); cout<<str<<endl; return 0; }