1024programmer Blog Reverse a set of strings and enter “sing dance rap basketball”. After reversing, you get “basketball rap dance sing”

Reverse a set of strings and enter “sing dance rap basketball”. After reversing, you get “basketball rap dance sing”

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

Insert image description here
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);
 }
 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/reverse-a-set-of-strings-and-enter-sing-dance-rap-basketball-after-reversing-you-get-basketball-rap-dance-sing/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索