实现一个函数,将一个字符串中的每个空格替换成 "%20"。
例如,当字符串为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; }