1. Remove the extra spaces:
e.g.
Before:life___is__short___i___use___python_ ' + ' (underline is a space)
After:life_is_short_i_use_python ' + ' (to remove the extra space)
Remove the space is relatively simple, we can judge the character, if there is a continuous space to move the array left until only one space, but this is very inefficient;
Before learning to use the fast subscript method to realize the idea of quick-line, here can also use a similar method:
For the deleted array, the length will be reduced or unchanged, then the subscript of the array after the delete is slow subscript, the other is fast subscript
!! For the time being, we do not consider how other whitespace characters are handled (assuming that the white space characters in the string array are only spaces):
1voidTrim_space (Char*STR)
2{
3intIndex_i=0, index_j=0;
4 while(Str[index_j]) {
5if(str[index_j]!=' '|| (str[index_j]==' '&&index_i!=0&&str[index_i-1]!=' ')){
6Str[index_i++]=str[index_j++];
7}Else{
8index_j++;
9}
Ten}
Oneif(str[index_i-1]==' '){
Astr[index_i-1]=' /';
-}Else{
-str[index_i]=' /';
the}
- }
Fast and slow subscript can also be used to convert spaces in a string into%020
' Convert to '%020 ':
And to get rid of the extra space, we first find two different index of traverse speed.
In this example, the converted array length is incremented, and if you take a backward-forward traversal, the pointer that traverses the new array is a fast pointer
1voidReserve_space (Char*STR)
2{
3intCount=0;
4intIndex
5 for(index=0; str[index];index++) {
6if(str[index]==' '){
7count++;
8}
9}
TenIndex=strlen (str);
Oneintindex_j=index+count*3;
A while(index_j>=0){
-if(str[index]!=' '){
-str[index_j--]=str[index--];
the}Else{
-str[index_j--]='0';
-str[index_j--]='2';
-str[index_j--]='0';
+str[index_j--]='%';
-index--;
+}
A}
at }
The use of speed subscript or fast pointer can be more convenient to solve a lot of problems must master this method
Manipulating string arrays with fast and slow subscripts