欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

利用java实现单词倒序排列

时间:2020-12-05 13:04:50|栏目:JAVA代码|点击:

本文就是会将数组里面的单词进行倒序排列 例如 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

示例代码    

public static void main(String[] args) {
    char[] chars= new String("How old are you !? I don't understand").toCharArray();
    System.out.println("the first:");
    System.out.println(chars);
     
    reverseWords(chars); //主要方法
     
    System.out.println("the second:");
    System.out.println(chars);
  }
 
   
  /**
   * 会将数组里面的单词 倒序排列 例如 how old are you -> you are old how
   * @param chars
   */
  public static void reverseWords(char[] chars) {
    reverseChars(chars,0,chars.length-1);
    int begin = -1;
    int end = 0;
    for(int i=0;i<chars.length;i++){
      char c = chars[i];
      if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||c=='\''){ //简单的判断了一下是否是连续的单词
        if(begin==-1){
          begin = i;
          end=i;
        }else{
          end=i;
          if(i==chars.length-1){
            reverseChars(chars,begin,end);
          }
        }
      }else{
        if(begin!=-1){
          reverseChars(chars,begin,end);
          begin=-1;
          end=0;
        }
      }
    }
  }
 
  /**
   * 将char 一定范围内的 字符 倒序排列 例如   hello -> olleh
   * @param chars 数组
   * @param begin 开始位置
   * @param end  结束位置
   */
  public static void reverseChars(char[] chars, int begin, int end) {
    while(end>begin){
      char c = chars[begin];
      chars[begin] = chars[end];
      chars[end] = c;
      begin++;
      end--;
    }
  }

以上就是利用java实现单词倒序排列,希望对大家能够理解,对大家有所帮助

上一篇:Hibernate Validation自定义注解校验的实现

栏    目:JAVA代码

下一篇:Java System类两个常用方法代码实例

本文标题:利用java实现单词倒序排列

本文地址:http://www.codeinn.net/misctech/29770.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有