搜索此博客

2013年2月15日星期五

Reverse a String, Rotate a String and Reverse a Sentence

Implement 3 functions using C
1. Reverse a string:
    input: "abcdef"
    output: "fedcba"

2. Rotate a string to right by k place
    input: "abcdefg", 2
    output "cdefgab"

3. Reverse a sentence
    input: "This is a test."
    output: "test. a is This"

C语言: reverseString
01 #include<stdio.h>
02 
03 void reverse(char *str, int start, int end)
04 {
05      while(start<end)
06      {
07          char temp=str[start];
08          str[start++]=str[end];
09          str[end--]=temp;        
10      }
11 }
12 
13 void rotate(char *p, int k)
14 {
15      if(p==NULL)
16          return;
17      int len=strlen(p);
18      reverse(p,0,k-1);
19      reverse(p,k, len-1);
20      reverse(p,0,len-1);
21 }
22 
23 void reverseSentence(char *str)
24 {
25      int len=strlen(str);
26      reverse(str,0,len-1);
27      int start;
28      int end=0;
29      while(end<len)
30      {
31          if(str[end]!=' ')
32          {
33              start=end;
34              while(end<len && str[end]!=' ')
35              {
36                  end++;
37              }
38              end--;
39              reverse(str,start,end);
40          }
41          end++;      
42      }  
43 }
44 
45 int main()
46 {
47     char str[]="abcdefg";
48     printf("Before rotation: %s\n", str);
49     int len=strlen(str);
50   
51     rotate(str,2);
52     printf("After rotation: %s\n", str);
53   
54     char sentence[]="This is a test.";
55     reverseSentence(sentence);
56     printf("%s\n",sentence);  
57   
58     printf("Press any key to continue...");      
59     getch();
60     return 0;
61 }

没有评论:

发表评论