利用java實現(xiàn)單詞倒序排列
本文就是會將數(shù)組里面的單詞進行倒序排列 例如 how old are you -> you are old how
示例程序輸出結(jié)果:
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); } /** * 會將數(shù)組里面的單詞 倒序排列 例如 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=='\''){ //簡單的判斷了一下是否是連續(xù)的單詞 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 一定范圍內(nèi)的 字符 倒序排列 例如 hello -> olleh * @param chars 數(shù)組 * @param begin 開始位置 * @param end 結(jié)束位置 */ 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實現(xiàn)單詞倒序排列,希望對大家能夠理解,對大家有所幫助
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)與算法之稀疏數(shù)組與隊列深入理解
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)與算法之稀疏數(shù)組與隊列深入理解,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09Java Config下的Spring Test幾種方式實例詳解
這篇文章主要介紹了Java Config下的Spring Test方式實例代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05Spring Boot Admin管理監(jiān)控數(shù)據(jù)的方法
本篇文章主要介紹了Spring Boot Admin管理監(jiān)控數(shù)據(jù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12Java編程中實現(xiàn)Condition控制線程通信
這篇文章主要介紹了Java編程中實現(xiàn)Condition控制線程通信,簡單介紹了Java中控制線程通信的方法,以及對condition的解析和實例,具有一定參考價值,需要的朋友可以了解下。2017-11-11