如何实现一个字符的反转 (Java)
一、.通过jdk自带reverse的方法。
二、如何写成Common直接调用。
1.将反转参数化方法
public class reverse {
//如何将数据abcdefg,进行返转输出
public static void main(String[] args) {
String a = "abcdefg";
StringBuffer b = new StringBuffer(a);
System.out.println(b.reverse().toString());
}
//将反转参数化方法
public String reversePrint(String parameter){
StringBuffer b = new StringBuffer(parameter);
return b.reverse().toString();
}
}
2. 调用反转方法。
public class debug {
static Common c = new Common();
static reverse r = new reverse();
public static void main(String[] args) {
String parameter = "abcd";
String resultShow = c.reversePrint(parameter);
System.out.println(resultShow);
String s = "How are You";
String resultShow2 = r.reverse2(s);
System.out.println(resultShow2);
}
}
三、通过自己写循环。 利用String.toCharArray()方法,将String转成一个char型数组,然后用数组遍历的方式从后向前遍历。
public static String reverse2(String s){
int length = s.length();
String reverse = "";
for (int i = 0; i < length; i++) {
reverse = s.charAt(i) + reverse;
}
return reverse;
}

浙公网安备 33010602011771号