Java将一个字符串的指定部分进行反转,比如“abcdef”反转为“aedcbf”

将一个字符串的指定部分进行反转,比如“abcdef”反转为“aedcbf”

public class stringdemo {
    
    
    /**
     * 将一个字符串的指定部分进行反转,比如“abcdef”反转为“aedcbf”
     */
    // 方式一:转换为char[]
    public String reverse(String str, int startIndex, int endIndex) {
    
    
        if (str != null && str.length() != 0) {
    
    
            char[] chars = str.toCharArray();
            for (int i = startIndex, j = endIndex; i < j; i++, j--) {
    
    
                char temp = chars[i];
                chars[i] = chars[j];
                chars[j] = temp;
            }
            return new String(chars);
        }
        return null;
    }

    @Test
    public void test() {
    
    
        String str = "abcdef";
        String reverser = reverse(str, 2, 5);
        System.out.println(reverser);
    }


    // 方式二 ;使用String的拼接
    public String reverse1(String str, int startIndex, int endIndex) {
    
    
        String strReverser = str.substring(0, startIndex);
        for (int i = endIndex; i >= startIndex; i--) {
    
    
            strReverser += str.charAt(i);
        }
        strReverser += str.substring(endIndex + 1);
        return strReverser;
    }


    @Test
    public void test1() {
    
    
        String str = "abcdef";
        String reverser = reverse1(str, 2, 5);
        System.out.println(reverser);
    }
}

猜你喜欢

转载自blog.csdn.net/E_chos/article/details/113345120
今日推荐