用“%20”取代字符串中空格的时间复杂度为O(n)的算法
1 /*length 为字符串数组string的总容量*/ 2 void ReplaceBlank(char stringp[],int length) 3 { 4 if(string==NULL &&length<=0) 5 return; 6 7 /*originalLength 为字符串string的实际长度*/ 8 int originalLength=0; 9 int numberOfBlank=0; 10 int i=0; 11 while(string[i] !='\0') 12 { 13 ++originalLength; 14 15 if(string[i]==' ') 16 ++numberOfBlank; 17 ++i; 18 } 19 20 /*newlength 为把空格替换成%20之后的长度*/ 21 int newLength=originalLength+numberOfBlank*2; 22 if(newLength >length) 23 return; 24 25 int indexOfOriginal = originalLength; 26 int indexOfNe = newLength; 27 while(indexOfOriginal >=0 && indexOfNew >indexOfOriginal) 28 { 29 if(string[indexOfOriginal] ==' ') 30 { 31 string[indexOfNew --] ='0'; 32 string[indexOfNew --] ='2'; 33 string[indexOfNew --] ='%'; 34 } 35 else 36 { 37 string[indexOfNew --]=string[indexOfOriginal]; 38 } 39 40 --indexOfOriginal; 41 } 42 }