Algorithm idea: first reverse the entire array, and then reverse the order of each word in the array
#include<stdio.h> #include<assert.h> int my_strlen(const char*str)//implement strlen function by yourself { int count=0; assert(str!=NULL);//Specify that str cannot be a null pointer, assert, optimize the function while(*str)//Dereference, take element { count++; str++; } return count; } void reverse_str(char *left,char *right)//Reverse order function { assert(left!=NULL); assert(right!=NULL); while(left<right) { char tmp=*left; *left=*right; *right=tmp; left++; right--; } } void reverse(char *str) { char *left=str; char *right=str+my_strlen(str)-1; char * ret = str; reverse_str(left,right); while(*ret)//Reverse order each word { char *start=ret;//Dereference, the first element while((*ret!=' ')&&(*ret!='\0'))//The words are broken with ' ', and the array ends with '/0' { ret ++; } reverse_str(start,ret-1);//Call the reverse order function if(*ret==' ')//Only when ret is ' ', ret ++ skips ' ' and reverses the next word { ret ++; } } } intmain() { char arr[]="student a am i"; reverse(arr); printf("%s",arr); return 0; }
The assert
() macro is used to ensure that a certain condition is met. The usage is:
assert(expression);
If the expression evaluates to false, the entire program exits with an error message. If the expression evaluates to true, the execution of the following statement continues.
Before using this macro, you need to include the header file assert.h
Before using this macro, you need to include the header file assert.h
Use of const: 1. When const modifies a pointer, const is placed on the left side of *, and the content pointed to by the pointer cannot be passed
If the pointer is changed, the pointer variable itself can be changed
. 2. When const is placed to the right of *, the content pointed to by the pointer can be changed through the pointer, but the pointer variable itself cannot be changed.
. 2. When const is placed to the right of *, the content pointed to by the pointer can be changed through the pointer, but the pointer variable itself cannot be changed.