/**
* @author 大跳蚤
* @create 2020-11-28
* @describe 将一个字符串进行反转。将字符串中指定部分进行反转。比如 “abcdefg” 反转为 ”abfedcg”
*/
public class partreverseTest {
//法一使用char[]
public void reverse(String str,int start,int end) {
char array[] = str.toCharArray();
for (int x = start, y = end ; x < y ; x++ , y--){
char temp = 0;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
String newstr = new String(array);
System.out.println(newstr);
}
//法二使用substring()
public void reverse1(String str,int start,int end){
String newstr = str.substring(0,start);
for(int i = end ; i >= start ; i--){
newstr = newstr + str.charAt(i);
}
newstr = newstr + str.substring(end+1);
System.out.println(newstr);
}
// 法三使用StringBuffer/StringBuilder
public void reverse2(String str,int start,int end){
String newstr = str.substring(0,start);
StringBuffer substr = new StringBuffer(str.substring(start,end+1));
newstr = newstr + substr.reverse();
newstr = newstr + str.substring(end+1);
System.out.println(newstr);
}
@Test
public void testreverse(){
String str = "abcdefg";
// reverse(str,2,5);
// reverse1(str,2,5);
reverse2(str,2,6);
}
}
java练习之字符串的部分反转
最新推荐文章于 2022-04-23 17:22:05 发布