单词翻转

来源:互联网 发布:淘宝淘口令有危险吗 编辑:程序博客网 时间:2024/05/16 12:07

题目描述:

给出一个英语句子,希望你把句子里的单词顺序都翻转过来

输入:

输入包括一个英语句子

输出:

按单词的顺序把单词倒序输出

样例输入

I love you

样例输出

you love I

提示

注意单词之间的空格,最后一个可以有空格

#include <stdio.h>#include<string.h>char a[100000];char b[100000];char c[100000];int temp=0;void changeword(int start,int end);//转换单词 int main(){gets(a);int len=strlen(a);for(int i=0;i<len;i++)//字符串整体全部换位 { b[i]=a[len-1-i];}strncpy(c,b,len);//用数组c避免数组b在应用过程中有所改变 int i;{int k=0;while(b[k]==' ')//分析字串最后出现空格的情况 k++;for( i=k;i<len;i++){if(b[i]==' '){changeword(temp,i);// temp为单词转换开始位,i为结束位 temp=i+1;}}//最后一组数据单独列出来转换 changeword(temp,i);}//输出数据 for(int j=0;j<len;j++)printf("%c",c[j]); return 0;}void changeword(int start,int end){int t=start;while(end>t){c[start]=b[end-1];start++;end--;}}
JAVA代码:

public static void main(String[] args) {System.out.println(reverse("i love you"));}public static String reverse(String s){      int pos=0;      StringBuilder sb=new StringBuilder();      for(int i=0;i<s.length();i++){          char c=s.charAt(i);          if(c==' '){              pos=0;          }          sb.insert(pos,c);        if(c!=' '){              pos++;          }      }      return sb.toString();     }