将字符串反转,但单词不倒置。

Right here waiting for you!    ->    you! for waiting here Right

代码1:

 1 //将字符串反转,但单词不倒置。
 2 
 3 #include<stdio.h>
 4 #include<string.h>
 5 
 6 void reverse(char *s)
 7 {
 8     char data[255][255];//将s中的空格和非空格子串进行存储
 9     int row = 0,column = 0;
10     int i,j,k;
11 
12     for(i=0;s[i];)
13     {
14         data[row][column] = s[i];
15         column++;
16 
17         //找到了空格子串的开头
18         if(s[i] == ' ')
19         {
20             i++;
21             if(s[i] == ' ')
22             {
23                 do
24                 {
25                     data[row][column++] = s[i++];
26                 }while(s[i] == ' ');
27 
28                 data[row++][column] = '';
29                 column = 0;
30             }
31             else
32             {
33                 data[row++][column] = '';
34                 column = 0;
35             }
36         }
37 
38         //找到了非空格子串的开头
39         else if(s[i] != ' ')
40         {
41             i++;
42             if(s[i] != ' ')
43             {
44                 do
45                 {
46                     data[row][column++] = s[i++];
47                 }while(s[i] != ' ' && s[i]);//注意非空格字符还包括字符串结束符。
48 
49                 data[row++][column] = '';
50                 column = 0;
51             }
52             else
53             {
54                 data[row++][column] = '';
55                 column = 0;
56             }
57         }
58     }
59 
60     //将data[][]里面的子串存放于s中。
61     k = 0;
62     for(i=row-1;i>=0;i--)
63     {
64         for(j=0;data[i][j]!='';j++)
65         {
66             s[k++] = data[i][j];
67         }
68     }
69     s[k] = '';
70 }
71 
72 int main()
73 {
74     char s[255];
75     gets(s);
76     reverse(s);
77     puts(s);
78 }

代码2:

 1 //将字符串反转,但单词不倒置。Right here waiting for you! -> you! for waiting here Right
 2 #define _CRT_SECURE_NO_WARNINGS
 3 #include <stdio.h>
 4 #include <string.h>
 5 
 6 int main() 
 7 {
 8     char str[255];
 9     char result[255];
10     int length;
11     int i,j,k = 0;
12     int wordLen = 0;
13 
14     gets(str);
15     length = strlen(str);
16 
17     for (i = length-1; i >= 0; i--)
18     {
19         if (str[i] == ' ')
20         {
21             if (wordLen != 0)
22             {
23                 for (j = i + 1; j <= i + wordLen; j++)
24                 {
25                     result[k++] = str[j];
26                 }
27             }
28             result[k++] = ' ';
29             wordLen = 0;
30         }
31         else
32         {
33             wordLen++;
34         }
35     }
36     if (wordLen != 0)
37     {
38         for (j = 0; j < wordLen; j++)
39         {
40             result[k++] = str[j];
41         }
42     }
43     result[k] = '';
44     printf("%s", result);
45     return 0;
46 }
原文地址:https://www.cnblogs.com/Camilo/p/3838118.html