C++中给字符数组赋值报错,求指导

C++语言 码拜 8年前 (2016-04-26) 1829次浏览
一道编程题,替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
本人的代码

#include <iostream>
#include <string>
using namespace std;
int main()
{
	char *str = "We Are Happy";
	int i = 0, j, length = 12;
	while (str[i] != "\0")
	{
		if (str[i] == " ")
		{
			length += 2;
			for (j = length - 3; j > i; j--)
				str[j + 2] = str[j];
			str[i] = "%";
			str[i + 1] = "2";
			str[i + 2] = "0";
		}
		++i;
	}
	cout << str << endl;


	system("pause");
	return 0;
}

程序在网站上测试通过,但在vs2013上运行到str[j+2]=str[j]这行报错,字符数组不能赋值,求指导
C++中给字符数组赋值报错,求指导

解决方案

5

#include <iostream>
#include <string>
using namespace std;
int main()
{
	char *str = "We Are Happy";
	string strdst;
	int i = 0, length = 12;
	while (str[i] != "\0")
	{
		if (str[i] == " "){
			strdst+="%20";
		}
		else{
			strdst += str[i];
		}
		++i;
	}
	cout << strdst << endl;
	system("pause");
	return 0;
}

20

char *str = “We Are Happy”;是在常量区的字符串,不能进行修改,这句改成:char str[] = “We Are Happy”;
另外,由于你向后移动了字符串,要在最后补充上\0

20

VS下把”We Are Happy”这样的常量字符串放在常量区,该区域不允许进行写操作
你网站上的编译器本人猜肯定是GCC
单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。

5

仅供参考:

#include <stdio.h>
#include <string.h>
char s[256];
char *p;
int r,n,i;
int main() {
    while (1) {
        printf("请输入一行文字(空行结束),"%%20"将替换为" ","你懂得"将替换为"XXXXXX":\n");
        fgets(s,256,stdin);
        if ("\n"==s[0]) break;
        p=s;
        while (1) {
            p=strstr(p,"%20");
            if (p) {
                memmove(p+1,p+3,strlen(p)-3+1);
                p[0]=" ";
            } else break;
        }
        p=s;
        while (1) {
            p=strstr(p,"你懂得");
            if (p) {
                memmove(p+6,p+6,strlen(p)-6+1);
                for (i=0;i<6;i++) p[i]="X";
            } else break;
        }
        printf("%s",s);
    }
    return 0;
}
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//abcdefg%20helloworld%20something.pdf
//abcdefg helloworld something.pdf
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//这是测试文字你懂得,在这个你懂的地方,就得做你懂得的事
//这是测试文字XXXXX,在这个你懂的地方,就得做XXXXX的事
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++中给字符数组赋值报错,求指导
喜欢 (0)
[1034331897@qq.com]
分享 (0)