黑马程序员技术交流社区

标题: 自己定义的翻转字符串功能 [打印本页]

作者: 知足、遗忘    时间: 2015-9-9 22:09
标题: 自己定义的翻转字符串功能
package com.sf;

import java.util.*;
public class test4 {
       
        public static void main(String[] args){
               
                System.out.println("请输入一个字符串");
               
                Scanner sc = new Scanner(System.in);
                String s  = sc.nextLine();
                s = reverse(s);
                System.out.println(s);
                sc.close();
               
        }
        private static String reverse(String s){
                //将字符串转成字符数组
                char[] ch = s.toCharArray();
                int x = 0;
                //把字符数组的首尾交换位置
                while(ch.length-x-1>=x){
                        swap(ch,ch.length-x-1,x);
                        x++;       
                }
                return new String(ch);
        }
        //交换位置
        private static void swap(char[] ch,int a,int b){
                        char temp = ch[b];
                        ch[b] = ch[a];
                        ch[a] = temp;
        }
               
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2