Description:
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 .".
Analysis description:
Method 1: for a given string, you can traverse the entire string from front to back. When the first space is encountered, replace the space with "% 20" and move the subsequent characters backward, when the second space is encountered, replace the space with "% 20", move the characters following it backward, and so on until the terminator '\ 0' is encountered '. The advantage of this method is that it is easy to understand. It is determined that the subsequent characters must be moved more than once, and the time complexity of the algorithm is O (n * n ).
Method 2: think about this problem in the opposite way, and replace the former with the latter with the former one. In this way, only one character needs to be moved. The time complexity is O (n ). 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.
Program example:
#include <stdio.h>#include <stdlib.h>#include <string.h>void replaceblank(char string[], int length);intmain(int argc, char **argv){char string[1000] = "We are happy.";replaceblank(string, 1000);return -1;}void replaceblank(char string[], int length){if(string == NULL || length <= 0){printf("element fail.\n");return;}intoriginallength = 0;int numberofblank = 0;int i = 0;while(string[i] != '\0'){originallength++;if(string[i] == ' ')numberofblank++;++i;}int newlength = originallength + numberofblank * 2;if(newlength > length)return;int indexoforiginal = originallength;int indexofnew = newlength;while(indexoforiginal >= 0 && indexofnew > indexoforiginal){if(string[indexoforiginal] == ' '){string[indexofnew--] = '0';string[indexofnew--] = '2';string[indexofnew--] = '%';}else{string[indexofnew--] = string[indexoforiginal];}indexoforiginal--;}printf("string[1000] = %s\n", string);}After compilation, the running result is as follows:
String [1000] = We % 20are % 20happy.
Summary:
1. for strings, the reverse thinking is also a way of thinking from the back to the back.
2. When the character array is used as a function parameter, the pointer to the first element of the array is actually passed.