例23:将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
public class StringDemo {
//方式一
public String reverse(String str,int startIndex,int endIndex){
if(str!=null){
char[] arr=str.toCharArray();
for (int x = startIndex,y= endIndex; x < y; x++,y--) {
char temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
return new String(arr);
}
return null;
}
//方式二
public String reverse1(String str,int startIndex,int endIndex){
if(str!=null){
String s2=str.substring(0,startIndex);
for (int i =endIndex; i >=startIndex; i--) {
s2+=str.charAt(i);
}
s2+=str.substring(endIndex+1);
return s2;
}
return null;
}
//方式三
public String reverse2(String str,int startIndex,int endIndex){
if(str!=null){
StringBuilder s3=new StringBuilder(str.length());
s3.append(str.substring(0,startIndex));
for (int i =endIndex; i >=startIndex; i--) {
s3.append(str.charAt(i));
}
s3.append(str.substring(endIndex+1));
return s3.toString();
}
return null;
}
@Test
public void test(){
String s1="abcdefg";
String reverse=reverse(s1,2,5);
System.out.println(reverse);
}
}