替换空格
1 #include "stdafx.h" 2 #include <iostream> 3 #include <exception> 4 using namespace std; 5 6 /*替换空格*/ 7 /* 8 题目:请实现一个函数,把字符串中的每个空格替换成"%20".例如输入"We are happy",则输出"We%20are%20happy". 9 */ 10 int ReplaceBlank(char string[],int length) 11 { 12 int i = 0; 13 int blankNum=0; 14 int strLength=0; 15 while(string[i]!='\0') 16 { 17 strLength++; 18 if(string[i] == ' ') 19 { 20 blankNum++; 21 } 22 ++i; 23 } 24 int endIndex = strLength+blankNum*2; 25 if(endIndex > 99) 26 { 27 cout<<"数组长度不够!"<<endl; 28 return 0; 29 } 30 while(strLength>=0 && endIndex>strLength) 31 { 32 if(string[strLength] != ' '){ 33 string[endIndex] = string[strLength]; 34 endIndex--; 35 } 36 else 37 { 38 string[endIndex--]='0'; 39 string[endIndex--]='2'; 40 string[endIndex--]='%'; 41 } 42 strLength--; 43 } 44 return 1; 45 46 } 47 int _tmain(int argc, _TCHAR* argv[]) 48 { 49 char str[100]="hello w o rld"; 50 ReplaceBlank(str,100); 51 cout<<str<<endl; 52 return 0 ; 53 }