代码片段(1)[全屏查看所有代码]
1. [代码]
01 | #include<stdio.h> |
02 | #include<string.h> |
03 | //翻转函数,将字符数组元素首尾互换 |
04 | void swapstr( char *head, char *tail) |
05 | { |
06 | while (head < tail){ |
07 | char c = *head; |
08 | *head = *tail; |
09 | *tail = c; |
10 |
11 | tail--; |
12 | head++; |
13 | } |
14 | } |
15 |
16 | int main( void ) |
17 | { |
18 | char str[128] = {0}; |
19 | |
20 | printf ( "please input a sentence:\n" ); |
21 | // scanf("%s",str); |
22 | //此处建议使用fgets()函数,fgets()能够接收到空格和回车 |
23 | fgets (str,128,stdin); |
24 | //去掉接收到的回车符 |
25 | str[ strlen (str)-1] = '\0' ; |
26 |
27 | char *p,*head,*tail; |
28 |
29 | p = head = tail =&str[0]; |
30 | |
31 | while (*tail != '\0' ){ |
32 | tail++; |
33 | } |
34 | tail -= sizeof ( char ); //定位最后一个字符的位置 |
35 | swapstr(head,tail); //将整句话按照字母翻转 |
36 |
37 | while (*p != '\0' ){ |
38 | //翻转字符数组中的单词 |
39 | if (*p == ' ' ){ |
40 | tail = p - sizeof ( char ); |
41 | swapstr(head,tail); |
42 | head = ++p; |
43 | } |
44 | //此处用while()或者if(),if版本参见源码 |
45 | while (*head == ' ' ){ |
46 | head++; |
47 | } |
48 |
49 | p++; |
50 | } |
51 | //最后一个单词的翻转 |
52 | if (*p == '\0' ){ |
53 | tail = p - sizeof ( char ); |
54 | swapstr(head,tail); |
55 | } |
56 | |
57 | puts (str); |
58 | |
59 | return 0; |
60 | } |