例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
void replaceSpace(char *str,int length) { string s(str); while (true) { int index = s.find(' '); if (index == s.npos) break; s.replace(index, 1, "%20"); } strcpy(str, s.c_str()); }
這里要將string對象轉化為char*對象,有如下方法:
1、可以使用string提供的函數 c_str() ,或是函數data(),data除了返回字符串內容外,不附加結束符'\0',而 c_str() 返回一個以 '\0' 結尾的字符數組。
2、const char* c_str();
const char* data();
注意:一定要使用strcpy()函數等來操作方法c_str()返回的指針
比如:
最好不要這樣:
char* c;
string s="1234";
c = s.c_str(); //編譯出錯,不能將const char* 變量賦值給char* 變量
應該這樣用:
char c[20];
char* c1 = new char [];
string s = "1234";
strcpy(c, s.c_str());
strcpy(c1, s.c_str());
調用函數並測試結果:
#include <vector> #include <string> #include <iostream> #include <typeinfo> using namespace std; void replaceSpace(char *str, int length) { string s(str); while (true) { int index = s.find(' '); if (index == s.npos) break; s.replace(index, 1, "%20"); } strcpy(str, s.c_str()); } int main() { char *c1 = new char[100]; strcpy(c1, "e e w d s a"); replaceSpace(c1, 100);//以c1為參數 char c2[100] = "wqe ewq"; replaceSpace(c2, 100);//以c2為參數 cout << c1 << endl;//e%20%20%20%20e%20w%20d%20s%20a cout << c2 << endl;//wqe%20ewq return 0; }