class=”markdown_views prism-atom-one-dark”>
Reverse a group of strings, for example, enter “sing dance rap basketball”
After reversing, you will get such a string
“basketball rap dance sing”
The idea is as follows:
First, convert the entire string Reverse group string
llabteksab par ecnad gnig
Then reverse each word in it
You can also reverse each word first, and then reverse the entire string
The specific code is as follows
void Reverse(char* start, char* end){
//Pass the beginning and end pointers and reverse the string
char tmp;
while (start < end){
tmp = *start;
*start = *end;
*end = tmp;
start++;
end--;
}
}
void reversestring(char*src){
int i;
char* start = src;
char* end;
for (i = 0; src[i]; i++){
//Iterate through the array
if (src[i] == ' '){
end = src + i - 1;//i is the position of the space, end is the one before the space
Reverse(start, end);
start = src + i + 1;
}
}
end = src + i - 1;
Reverse(start, end);
Reverse(src, end);
}
int main(){
char src[] = "sing dance rap basketball";
reversestring(src);
puts(src);
system("pause");
return 0;
}
What needs to be noted here is that in the for loop, the entire array is traversed. In this loop, only the three words sing dance rap
have been reversed, because the following digits are all ‘ ‘
and ” “sing dance rap basketball” ends with \0, that is, basketball has not completed the inversion
We need to recycle the outer pass to invert it
The results are as follows
You can also use library functions to solve this problem
The code is as follows:
void reverseStringS(char * src)
{
char*tmp;
char dest[100] = { 0 };
while (tmp = strrchr(src, ' '))
{
strcat(dest, tmp + 1);
strcat(dest, " ");
*tmp = 0;
}
strcat(dest, src);
strcpy(src, dest);
}