/*
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为
We%20Are%20Happy。
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Solution {
public:
void replaceSpace(char *str, int length) {
for (int i = 0; i < length; ++i){
if (*(str + i) == ' '){
length += 2;
memset(str + length-2, 0, 2);
for (int j = length-1; j > i; --j){
*(str + j) = *(str + j - 2);
}
*(str + i) = '%';
*(str + i + 1) = '2';
*(str + i + 2) = '0';
++i;
++i;
}
}
*(str + length) = '\0';
}
};
void foo()
{
char str[100] = "We Are Happy";
int len = strlen(str);
Solution sol;
sol.replaceSpace(str, len);
cout << str << endl;
//如果返回时,str数组长度出现了变化,就会出现Stack around the variable 'str' was corrupted
}
int main()
{
foo();
return EXIT_SUCCESS;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。