public static String partReverse(String string,int begin,int end){
String s1 = string.substring(0, begin);
String s2 = string.substring(begin, end);
String s3 = string.substring(end);
//只反转中间的部分
char[] chars = s2.toCharArray();
for (int i = 0; i < chars.length / 2; i++) {
char tmp = chars[i];
chars[i] = chars[chars.length - 1 - i];
chars[chars.length - 1 - i] = tmp;
}
s2 = new String(chars);
//再拼接
String result = s1 + s2 + s3;
return result;
}
public void test7() {
String str1 = "abcdefghijklmn";
int begin = 2;//包含
int end = 6;//不包含
System.out.println(partReverse(str1, begin, end));
}
Java字符串 substring实现部分反转
最新推荐文章于 2024-08-15 14:47:41 发布