- #include<stdio.h>
- #include<string.h>
- //翻转函数,将字符数组元素首尾互换
- void swapstr(char *head,char *tail)
- {
- while(head < tail){
- char c = *head;
- *head = *tail;
- *tail = c;
- tail--;
- head++;
- }
- }
- int main(void)
- {
- char str[128] = {0};
- printf("please input a sentence:\\n");
- // scanf("%s",str);
- //此处建议使用fgets()函数,fgets()能够接收到空格和回车
- fgets(str,128,stdin);
- //去掉接收到的回车符
- str[strlen(str)-1] = '\\0';
- char *p,*head,*tail;
- p = head = tail =&str[0];
- while(*tail != '\\0'){
- tail++;
- }
- tail -= sizeof(char);//定位最后一个字符的位置
- swapstr(head,tail);//将整句话按照字母翻转
- while(*p != '\\0'){
- //翻转字符数组中的单词
- if(*p == ' '){
- tail = p - sizeof(char);
- swapstr(head,tail);
- head = ++p;
- }
- //此处用while()或者if(),if版本参见源码
- while(*head == ' '){
- head++;
- }
- p++;
- }
- //最后一个单词的翻转
- if(*p == '\\0'){
- tail = p - sizeof(char);
- swapstr(head,tail);
- }
- puts(str);
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/140520149573.html
来源: http://www.codesnippet.cn/detail/140520149573.html