一、题目:
定义一个方法,实现字符串反转。
键盘录入一个字符串,调用该方法后,在控制台输出结果。
例如,键盘录入abc,输出结果cba。
二、重难点:
反向遍历。
三、代码:
public class StringReversal {
public static void main(String[] args) {
String result = reversal("abc");
System.out.println(result);
}
public static String reversal(String str) {
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
//i依次表示字符串中倒着的每一个索引
char c = str.charAt(i);
result = result + c;
}
return result;
}
}