Hi all,
This C program reverses the first n words in a string, for example:
echo "hello world do not reverse" | rev 2 should output:
"world hello do not reverse"
Here's my code:
The above code should reverse all the words in the string. How can I modify the code so it'll be for the first n words only?Code:1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <ctype.h> 4 #include <string.h> 5 6 void swap(char* str, int i, int j) { 7 char t = str[i]; 8 str[i] = str[j]; 9 str[j] = t; 10 } 11 12 void reverse_string(char* str, int length) { 13 int i; 14 for (i = 0; i < length / 2; i++) 15 swap(str, i, length - i - 1); 16 } 17 18 int main(int argc, char *argv[]) { 19 char str[1024]; 20 char chars[1024]; 21 int l; 22 int p; 23 int i; 24 if (argc != 2) { 25 printf("Invalid argument"); 26 return 1; 27 } 28 if (atoi(argv[1]) <= 0) { 29 printf("Invalid argument"); 30 return 2; 31 } 32 str[0] = '\0'; 33 while (fgets(chars, 1024, stdin)) 34 strcat(str, chars); 35 l = strlen(str); 36 reverse_string(str, l); 37 p = 0; 38 for(i = 0; i < l; i++) { 39 if(str[i] == ' ') { 40 reverse_string(&str[p], i - p); 41 p = i + 1; 42 } 43 } 44 reverse_string(&str[p], l - p); 45 printf("%s\n", str); 46 return 0; 47 }
Thanks in advance



1Likes
LinkBack URL
About LinkBacks



