Using Java to achieve word order in reverse order

  • 2020-04-01 04:04:56
  • OfStack

This article will just sort the words in the array in reverse order like how old are you -> You are old how

Sample program output result:

The first:
How old are you! The & # 63; I don 't understand
The second:
I understand, don 't & # 63; ! You are old How

The sample code        


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); //The main method
     
    System.out.println("the second:");
    System.out.println(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=='''){ //Simply determine if it is a continuous word
        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;
        }
      }
    }
  }
 
  
  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--;
    }
  }

Above is the use of Java to achieve reverse word order, I hope you can understand, to help you


Related articles: