面试官最喜欢问初级Java开发的问题:如何“hello world“的顺序逆转

面试背景

当你还是刚踏入社会的应届生时,你是否充满对未来生活的美好期待,却不知面试官的“险恶”,让你倍受折磨,看完这篇让你面试几率大大增加。

将“hello world”转换为dlrow olleh

通过StringBuffer自带的reverse()方法实现反转

public static void main(String[] args) {
        String str="hello world";
        StringBuffer sbf=new StringBuffer(str);
        System.out.println(sbf.reverse().toString());//输出drow olleh
}

将“hello world”转换为world hello

使用字符串对空格的切割,从数组最后一个循环开始依此递减,实现顺序调换

public static void main(String[] args) {
        String str="hello world";
        StringBuffer sbf=new StringBuffer();
        //字符串分割
        String [] arr=str.split(" ");
        for(int i=arr.length-1;i>=0;i--){
            sbf.append(arr[i]+" ");
        }
        System.out.println(sbf.toString())
}

猜你喜欢

转载自blog.csdn.net/qq_39940674/article/details/90239390
今日推荐