免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1434 | 回复: 0

将单词倒序排列 [复制链接]

论坛徽章:
0
发表于 2015-07-13 10:58 |显示全部楼层
会将数组里面的单词 倒序排列 例如 how old are you -> you are old how

示例程序输出结果:
the first:
How old are you !? I don't understand
the second:
understand don't I ?! you are old How

示例代码
  1. public static void main(String[] args) {
  2.         char[] chars= new String("How old are you !? I don't understand").toCharArray();
  3.         System.out.println("the first:");
  4.         System.out.println(chars);
  5.          
  6.         reverseWords(chars);  //主要方法
  7.          
  8.         System.out.println("the second:");
  9.         System.out.println(chars);
  10.     }

  11.      
  12.     /**
  13.      * 会将数组里面的单词 倒序排列  例如  how old are you -> you are old how
  14.      * @param chars
  15.      */
  16.     public static void reverseWords(char[] chars) {
  17.         reverseChars(chars,0,chars.length-1);
  18.         int begin = -1;
  19.         int end = 0;
  20.         for(int i=0;i<chars.length;i++){
  21.             char c = chars[i];
  22.             if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||c=='\''){ //简单的判断了一下是否是连续的单词
  23.                 if(begin==-1){
  24.                     begin = i;
  25.                     end=i;
  26.                 }else{
  27.                     end=i;
  28.                     if(i==chars.length-1){
  29.                         reverseChars(chars,begin,end);
  30.                     }
  31.                 }
  32.             }else{
  33.                 if(begin!=-1){
  34.                     reverseChars(chars,begin,end);
  35.                     begin=-1;
  36.                     end=0;
  37.                 }
  38.             }
  39.         }
  40.     }

  41.     /**
  42.      * 将char 一定范围内的 字符 倒序排列  例如      hello -> olleh
  43.      * @param chars 数组
  44.      * @param begin 开始位置
  45.      * @param end   结束位置
  46.      */
  47.     public static void reverseChars(char[] chars, int begin, int end) {
  48.         while(end>begin){
  49.             char c = chars[begin];
  50.             chars[begin] = chars[end];
  51.             chars[end] = c;
  52.             begin++;
  53.             end--;
  54.         }
  55.     }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP