Replace spaces. Replace spaces in excel.
Question: implement a function to replace each space in the string with "% 20 ". For example, if "We are happy." Is input, "We % 20are % 20happy." Is output .".
Idea: We can traverse the string first, so that we can calculate the total number of spaces in the string and calculate the total length of the string after replacement. Each replacement of a space increases by 2. Therefore, the length of the string after replacement is equal to the original length plus 2 multiplied by the number of spaces. We use the string "We are happy. "For example," We are happy. "The length of this string is 14 (including the ending sign '\ 0'), which contains two spaces. Therefore, the length of the string after replacement is 18.
We Start copying and replacing strings. First, prepare two pointers, P1 and P2. P1 points to the end of the original string, while P2 points to the end of the replaced string (). Next we move the pointer P1 forward and copy the characters it points to the position pointed to by P2 one by one until the first space is reached. In this case, the string contains (B), and the area of the gray background is the area where the characters are copied (moved. When the first space is reached, move P1 forward to the first space and insert the string "% 20" before P2 ". Since the length of "% 20" is 3, P2 must also be moved forward, as shown in 3 cells (c.
We copy it forward until we encounter the second space (d ). Like the previous one, we move P1 forward to 1 lattice and insert P2 forward to 3 lattice "% 20" (e ). In this caseP1 and P2 point to the same position, indicating that all spaces have been replaced.
1 # include <string> 2 # include "stdafx. h "3 4 void ReplaceBlank (char string [], int length) 5 {6 if (string = NULL & length <= 0) 7 return; 8 9 int originalLength = 0; 10 int numberOfBlank = 0; 11 int I = 0; 12 13 while (string [I]! = '\ 0') 14 {15 + + originalLength; 16 17 if (string [I] = '') 18 ++ numberOfBlank; 19 20 + I; 21} 22 23 // newLength: Replace the space with the length 24 int newLength = originalLength + numberOfBlank * 2 after '% 20'; 25 if (newLength> length) 26 return; 27 28 int indexOfOriginal = originalLength; 29 int indexOfNew = newLength; 30 31 // skip 32 while without spaces (indexOfOriginal> = 0 & indexOfNew> indexOfOriginal) 33 {34 if (string [indexOfOriginal] = '') 35 {36 string [indexOfNew --] = '0'; 37 string [indexOfNew --] = '2 '; 38 string [indexOfNew --] = '%'; 39 // use minus 40} 41 else42 {43 string [indexOfNew --] = string [indexOfOriginal]; 44} 45 46 -- indexOfOriginal; 47} 48} 49 50 int main () 51 {52 const int length = 100; 53 54 char string [length] = "We are happy "; 55 printf ("% s \ n", string); 56 ReplaceBlank (string, length); 57 printf ("% s \ n", string ); 58 59 char string1 [length] = ""; 60 printf ("% s \ n", string1); 61 ReplaceBlank (string1, length ); 62 printf ("% s \ n", string1); 63 64 return 0; 65}