Friday, January 29, 2016

Reverse alternative order of words in a sentence

Reverse alternative order of words in a sentence


Reverse alternative order of words in a sentence.
Problem:
Reverse alternative order of words in a sentence.
i/p: This is for testing
o/p: is This testing for
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
void reverse(char *s, char *t)
{
 for( ; s < t; s++, t--) {
   char temp = *s;
        *s = *t;
        *t = temp;
 }
}
 
reverseWords(char *s)
{
  char *wordBegin = NULL;
  char *temp = s;
  char *stcBegin = s;
  int wordCount = 0;
  while(*temp) {
    if(wordBegin == NULL && *temp != ' ') {
      wordBegin = temp; 
      if(wordCount==0) {
         stcBegin = temp;
      }   
    }
    else if (wordBegin && *(temp+1)==' ' ||  *(temp+1)=='\0') {
      reverse(wordBegin, temp);
      wordBegin = NULL;
      wordCount++;   
    }
    if(wordCount>0 && wordCount%2==0) {
        reverse(stcBegin, temp);
        wordCount=0;
    }
      temp++;
  }
  
    
}
 
 
 
int main()
{
  char s[] = "This is for testing";
  char *temp = s;
  reverseWords(s);
  printf("%s", s); 
  return 0;
}
Click here for more Programming Interview Questions


No comments:

Post a Comment