- import java.util.Scanner;
- /*
- * 字符串反转
- * 举例:键盘录入"abc" 输出结果:"cba"
- * abcd dcba
- *
- * 方式一:将字符串倒序遍历,封装为一个新字符串,然后输出
- * 方式二:转换为char数组,将数组的元素,第一和最后一个对调,将第二个和倒数第二个对调....
- */
- public class Demo {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一句话:");
- String str = sc.next();
- //将str反转
- String result = "";
- for(int i = str.length() - 1 ; i >= 0 ; i--){
- result = result + str.charAt(i);//""+'c' //"c" + 'b' //"cb" + 'a' //"cba"
- }
- System.out.println("result = " + result);
-
- //方式二:转换为数组,对调元素
- char[] charArray = str.toCharArray();
- for(int i = 0;i < charArray.length / 2 ; i++){
- char c = charArray[i];//首
- charArray[i] = charArray[charArray.length - 1 - i];
- charArray[charArray.length - 1 - i] = c;
-
- }
- //将数组转换为String
- System.out.println("转换数组:" + new String(charArray));
- }
- }
复制代码- /*
- * 字符串反转:
- *
- * 1.将字符串转换为StringBuffer;
- * 2.调用StringBuffer的reverse():
- * 3.将StringBuffer转换为String;
- */
- public class Demo {
- public static void main(String[] args) {
- String str = "HelloWorld";
- //转换为StringBuffer
- StringBuffer buf = new StringBuffer(str);
- //调用方法,进行反转
- buf.reverse();
- //将StringBuffer转换为String
- String result = buf.toString();
-
- System.out.println("result = " + buf);
-
-
- }
- }
复制代码 |
|