Reference for programming exercises in Chapter C and pointer -- 6.3, c and pointer 6.3
C and pointer -- 6.3
Question:
Write a function to sort the characters in the parameter string in reverse order.
Function prototype:
Void reverse_string (char * string );
Requirements:
Use Pointer instead of array subscript
Do not use any C function library to manipulate strings.
Do not declare a local array to temporarily store parameter strings
Code:
# Include <stdio. h> void reverse_string (char * string) {int I, n = 0; while (* (string + n )! = '\ 0') // calculate the number of characters in the string plus n ++; n --; // The number of characters minus 1 when n is used as the index number, that is, from 0 to n-1 if (n> 0) // when the number of characters is less than or equal to 1, there is no need to reverse {for (I = 0; I <= (n/2 ); I ++) {if (I! = (N-I) {char p; // character content exchange p = * (string + I); * (string + I) = * (string + n-I); * (string + n-I) = p ;}}} int main () {char source [] = "ABCDEFGH "; printf ("Before reverse: \ n % s \ n", source); reverse_string (source); printf ("After reverse: \ n % s \ n", source ); getchar (); return 0 ;}
Note:
1. Calculate the number of non-\ 0 characters in the string.
2. Alternate first Character Exchange