Delete the blank characters at the beginning and end of the string, and convert multiple spaces (if any) in the middle of the array into one.
The writing is not very concise. There are several points worth special attention.
Method: two pointers. Space points to the first space, and letter points to the first letter after space. Then, the letter pointed to by letter is copied to the space pointed to by space.
Note the following:
1. Because a space is required between two words, space ++ is required before copying. Otherwise, no space is available.
2. As mentioned above, if this string is a space hitting header, as long as it is said that the final string will have one more space hitting header, so I added a flag in front to determine whether the string is a space hitting header.
3. When copying * letter to * space, you also need to set the letter to a space, or where her content is still.
In short, this code is generally written, and the total complexity will be slightly higher than O (N). O (n) can be solved, but I am horizontally limited, so .....
Calculate O (n) code sharing
# Include "stdafx. H "# include <iostream> using namespace STD; void switcher (char * Str) {char * letter = NULL; // point to the letter char * Space = NULL; // point to space bool flag = true; letter = space = STR; If (* STR = '') // prevent space from hitting the header, if you try it out, you will know why flag = false; while (* letter! = '\ 0') {While (* space! = ''& * Space! = '\ 0') // find the first space {space ++;} letter = space; while (* letter = ''& * letter! = '\ 0') // find the first letter after the space {letter ++;} If (* letter =' \ 0 ') // if there is no letter after this space, space is the end of the string {* Space = '\ 0'; return;} If (FLAG) Space ++; // if there are letters, there must be at least one space in the two character strings while (* letter! = ''& * Letter! = '\ 0') {* Space = * letter; * letter = ''; // The last one is very useful. If you try it out, you will know Space ++; letter ++;} flag = true;} int main () {char a [] = "Hello world baby ggg"; switcher (); cout <A <Endl; getchar (); Return 0 ;}