欢迎来到天天文库
浏览记录
ID:11262077
大小:46.00 KB
页数:5页
时间:2018-07-11
《java实现字符串倒序输出的几种方法》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Java实现字符串倒序输出的几种方法收藏1.最容易想到的估计就是利用String类的toCharArray(),再倒序输出数组的方法了。viewplaincopytoclipboardprint?importjavax.swing.JOptionPane;publicclassReverseString{publicstaticvoidmain(Stringargs[]){StringoriginalString;StringresultString="";originalString=JOptionPane.showInputDialog("PleaseinputaString:
2、");char[]charArray=originalString.toCharArray();for(inti=charArray.length-1;i>=0;i--){resultString+=charArray[i];}JOptionPane.showMessageDialog(null,resultString,"ReverseString",JOptionPane.INFORMATION_MESSAGE);}}importjavax.swing.JOptionPane;publicclassReverseString{publicstaticvoidmain(Strin
3、gargs[]){StringoriginalString;StringresultString="";originalString=JOptionPane.showInputDialog("PleaseinputaString:");char[]charArray=originalString.toCharArray();for(inti=charArray.length-1;i>=0;i--){resultString+=charArray[i];}JOptionPane.showMessageDialog(null,resultString,"ReverseString",J
4、OptionPane.INFORMATION_MESSAGE);}}2.还可以利用String类提供的subString()方法,利用递归的办法输出倒序字符串。viewplaincopytoclipboardprint?importjavax.swing.JOptionPane;publicclassReverseString{publicstaticvoidreverseString(Stringstr){if(str.length()==1){System.out.print(str);}else{StringsubString1=str.substring(0,str.len
5、gth()-1);StringsubString2=str.substring(str.length()-1);System.out.print(subString2);reverseString(subString1);}}publicstaticvoidmain(Stringargs[]){StringoriginalString;originalString=JOptionPane.showInputDialog("PleaseinputaString:");reverseString(originalString);}}importjavax.swing.JOptionPa
6、ne;publicclassReverseString{publicstaticvoidreverseString(Stringstr){if(str.length()==1){System.out.print(str);}else{StringsubString1=str.substring(0,str.length()-1);StringsubString2=str.substring(str.length()-1);System.out.print(subString2);reverseString(subString1);}}publicstaticvoidmain(Str
7、ingargs[]){StringoriginalString;originalString=JOptionPane.showInputDialog("PleaseinputaString:");reverseString(originalString);}}3.还有就是不把字符串定义为String类,而是定义成一个StringBuffer类,用StringBuffer类中的reverse()方法直接倒序字符串。viewplaincopytoclipboardprin
此文档下载收益归作者所有