//定义一个静态的字符串变量
public static String static_string = "";
/*
* 问题:如何反向输出字符串
* 1,用StringBuffer
*/
public static StringBuffer exchangeString_1(String str){
StringBuffer sb = new StringBuffer();
for(int i=0;i<str.length();i++){
sb.append(str.charAt(str.length() - (i+1)));
}
return sb;
}
/*
* 问题:如何反向输出字符串CHINA
* 2,用StringBuffer的reverse()方法
*/
public static String exchangeString_2(String str){
StringBuffer sb = new StringBuffer(str);
StringBuffer result = sb.reverse();
//for(int i=0;i<str.length();i++){
// sb.append(str.charAt(str.length() - (i+1)));
//}
return result.toString();
}
/*
* 问题:如何反向输出字符串CHINA
* 3,用数组arraylist
*/
public static String exchangeString_3(String str){
//定义一个ArrayList
ArrayList<Character> al = new ArrayList<Character>();
//把字符串str分割成char以后,存入ArrayList
for(int i=0;i<str.length();i++){
al.add(i, str.charAt(str.length()-(i+1)));
}
//将字符从ArrayList中取出,然后拼接成字符串
for(int j=0;j<al.size();j++){
//这里用到了递归调用
static_string = static_string.concat(al.get(j).toString());
}
return static_string;
}
这几种方法是比较常用的,一般我们都使用StringBuffer这个类中的方法,StringBuffer对于处理字符串还是很有用的。
写个主方法测试一下:
String stringTest = "ABC";
exchangeString_1(stringTest);
exchangeString_2(stringTest);
exchangeString_3(stringTest);
System.out.println("exchangeString_1(stringTest):" + exchangeString_1(stringTest));
System.out.println("exchangeString_2(stringTest):" + exchangeString_2(stringTest));
System.out.println("exchangeString_3(stringTest):" + exchangeString_3(stringTest));
运行结果:
exchangeString_1(stringTest):CBA
exchangeString_2(stringTest):CBA
exchangeString_3(stringTest):CBACBA