太久没用C了,C++string是以‘\0‘结尾,C总char*也是以‘\0‘结尾
但是用string.copy()方法得到的字符串并不是以‘\0结尾
----------------------------------------------------------------------------------------------
#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; }
原文:https://www.cnblogs.com/evidd/p/10560449.html