File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
151_reverse_words_in_a_string Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test reverse.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+ #include <string.h>
4+
5+ static reverse (char * s , int lo , int hi )
6+ {
7+ while (lo < hi ) {
8+ char c = s [lo ];
9+ s [lo ] = s [hi ];
10+ s [hi ] = c ;
11+ lo ++ ;
12+ hi -- ;
13+ }
14+ }
15+
16+ static void reverseWords (char * s )
17+ {
18+ int i = 0 , j = 0 ;
19+ while (s [i ] != '\0' ) {
20+ while (s [i ] == ' ' ) {
21+ i ++ ;
22+ }
23+ if (s [i ] == '\0' ) break ;
24+ while (s [i ] != '\0' && s [i ] != ' ' ) {
25+ s [j ++ ] = s [i ++ ];
26+ }
27+ s [j ++ ] = s [i ];
28+ }
29+ s [j ] = '\0' ;
30+ s [-- j ] = '\0' ;
31+ reverse (s , 0 , j - 1 );
32+
33+ for (i = 0 , j = 0 ; s [i ] != '\0' ;) {
34+ for (j = i ; s [j ] != '\0' && s [j ] != ' ' ; j ++ ) {}
35+ reverse (s , i , j - 1 );
36+ for (i = j ; s [i ] != '\0' && s [i ] == ' ' ; i ++ ) {}
37+ }
38+ }
39+
40+ int main (int argc , char * * argv )
41+ {
42+ if (argc != 2 ) {
43+ fprintf (stderr , "Usage: ./test string\n" );
44+ exit (-1 );
45+ }
46+ reverseWords (argv [1 ]);
47+ printf ("%s\n" , argv [1 ]);
48+ return 0 ;
49+ }
You can’t perform that action at this time.
0 commit comments