将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反 转为”abfedcg”

将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反
转为”abfedcg”

public class StringTest {
	
	//方法一
    public String reverse(String str,int begindex,int endIndex){

        if (str != null){
            char[] chars = str.toCharArray();
            for (int i = begindex,j = endIndex;i < j;i++,j--){
                char temp = chars[i];
                chars[i] = chars[j];
                chars[j] = temp;
            }
            return new String(chars);
        }

        return null;
    }

	//方法二
    public String reverse1(String str,int begindex,int endIndex){

        if (str != null){

            StringBuilder str2 = new StringBuilder(str.length());
            str2.append(str.substring(0,begindex));
            for (int i = endIndex;i >= begindex;i--){
                str2.append(str.charAt(i));
            }
            str2.append(str.substring(endIndex + 1));
            return new String(str2);

        }

        return null;
    }

    @Test
    public void test1 (){
        StringTest test = new StringTest();
        String str1 = "abcdefg";
//        int begIndex = 2;
//        int endIndex = 5;
        String s = test.reverse(str1, 2, 5);
        System.out.println(s);

        String s1 = test.reverse1(str1, 2, 5);
        System.out.println(s1);

    }
}
运行结果:
abfedcg
abfedcg

Process finished with exit code 0

你可能感兴趣的:(将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反 转为”abfedcg”)