【字符串】替换空格
/* 请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为 We%20Are%20Happy。 */ #define _CRT_SECURE_NO_WARNINGS #includeusing 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; }
标题名称:【字符串】替换空格
本文路径:http://myzitong.com/article/gjecdc.html