3431 - 颠倒的句子
读入一个字符串,按单词将该字符串逆序,比如给定"This is a sentence",则输出是"sentence a is This",为了简化问题,字符串中不包含标点符号。
Input
Output
Examples
Input
This is a sentence
Output
sentence a is This
Solution C
#include<stdio.h> #include<string.h> int main() { char a[1000],b[1000]={NULL}; gets(a); int len=strlen(a); a[len]=' '; a[len+1]='\0'; for(int i=len-1;i>=0;i--) { if(a[i]==' ') { strcat(b,a+i+1); a[i+1]='\0'; } } strcat(b,a); puts(b); }
Solution C++
#include <stdio.h> #include <stdlib.h> #include<iostream> #include <cstring> using namespace std; void ReverseWord(char* p, char* q) { while(p < q) { char t = *p ; *p++ = *q ; *q-- = t ; } } char* ReverseSentence(char* s) { char* p = s ; char* q = s ; while(*q != '\0') { if (*q == ' ') { ReverseWord(p, q - 1) ; q++ ; p = q ; } else q++ ; } ReverseWord(p, q - 1) ; ReverseWord(s, q - 1) ; return s ; } int main(){ char a[2001]; gets(a); printf("%s\n",ReverseSentence(a)); return 0; }