利用STL:
1 #include"iostream" 2 #include"stdio.h" 3 #include"algorithm" 4 using namespace std; 5 6 string ReplaceBlank(string src) 7 { 8 if(src.find(" ")>src.length()) 9 return src; 10 while(src.find(" ")<src.length()) 11 { 12 int pos=src.find(" "); 13 src=src.replace(pos,1,"%20"); 14 } 15 return src; 16 } 17 18 void Test(char *testName,string testStr,string resStr) 19 { 20 if(testName!=nullptr) 21 printf("the %s begin:",testName); 22 if(testStr=="") 23 { 24 printf("the source string is null!\n"); 25 return; 26 } 27 string res=ReplaceBlank(testStr); 28 if(res==resStr) 29 printf("passed.\n"); 30 else 31 printf("failed\n"); 32 } 33 34 //包含空格的字符串 35 void Test1() 36 { 37 Test("Test1","We are happy enough !","We%20are%20happy%20enough%20!"); 38 } 39 40 //不包含空格的字符串 41 void Test2() 42 { 43 Test("Test2","WeAreHappy","WeAreHappy"); 44 } 45 46 //空字符串 47 void Test3() 48 { 49 Test("Test3","",""); 50 } 51 52 int main() 53 { 54 Test1(); 55 Test2(); 56 Test3(); 57 return 0; 58 }