将一个字符串的指定部分进行反转,比如“abcdef”反转为“aedcbf”
public class stringdemo {
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);
}
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);
}
}