太久没用C了,C++string是以'\0'结尾,C总char*也是以'\0‘结尾
但是用string.copy()方法得到的字符串并不是以'\0结尾
----------------------------------------------------------------------------------------------
时间限制:1秒 空间限制:32768K 热度指数:871481
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
#include <string.h> #include <algorithm> #include <vector> #include <iostream> #include <string> using namespace std; class Solution { public: void replaceSpace(char *str,int length) { string strr(str); int pos; while ((pos = strr.find(" ")) != -1) { strr = strr.erase(pos, 1); strr = strr.insert(pos, "%20"); } strr.copy(str, strr.length()); // strcpy(str,strr.c_str()); str[strr.length()] = '\0'; cout<<str; } }; int main() { Solution demo; char s[] = "we are happy!"; demo.replaceSpace(s, 13); return 0; }