字符串比如“ad2 lsdkf,lksdjf. sdkfj”倒序排列"sdkfj lksdjf. lsdkf,ad2" 每个单词是空格分开,标点符号当作字母,不能用String的自带的一些方法,比如indexof,trim,split等方法。
public static void myConvert(String source) { char[] tmpArray = source.tocharArray(); StringBuffer out = new StringBuffer(); StringBuffer tmp = new StringBuffer(); for (int index = tmpArray.length - 1; index >= 0; index--) { if (tmpArray[index] == ' ') { out.append(" "); tmp.append(out); out.delete(0,out.length()); } else { out.insert(0,tmpArray[index]); } } tmp.append(out); System.out.println(tmp.toString()); }
使用了2个StringBuffer,有些笨重。下面的比较轻巧。
public static void reverseString(String source) { char[] cTemp = source.tocharArray(); String newString = ""; String sTemp = ""; for (int i = cTemp.length - 1; i >= 0; i--) { if (cTemp[i] == ' ') { newString += sTemp + cTemp[i]; sTemp = ""; } else { sTemp = cTemp[i] + sTemp; } } newString += sTemp; System.out.println(newString); }
这个程序是找别人的,很是轻巧学习。
此题源地址:http://www.iteye.com/topic/786985
原文链接:https://www.f2er.com/javaschema/287051.html