package string.exer;
import org.junit.Test;
/**
* @author
* @create 2022-01-13-13:32
* 将一个字符串进行反转,将字符串指定的部分进行反转,如ab cdef g -->ab fedc g
* <p>
* <p>
*/
public class StringDemo {
//方式二:使用String拼接操作
public String reverse1(String str, int startIndex, int endIndex) {
if (str != null) {
//第一部分
String str1 = str.substring(0, startIndex);
//第二部分
for (int i = endIndex; i >= startIndex; i--) {
str1 += str.charAt(i);
}
//第三部分
str1 += str.substring(endIndex + 1);
return str1;
} else {
return null;
}
}
//方式一:转换为char[]
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);
} else {
return null;
}
}
//方式三:使用StringBuffer/StringBuilder替换String
public String reverse2 (String str,int startIndex, int endIndex){
if (str != null) {
StringBuilder builder = new StringBuilder(str.length());
//第一部分
builder.append(str.substring(0, startIndex));
//第二部分
for (int i = endIndex; i >= startIndex; i--) {
builder.append(str.charAt(i));
}
//第三部分
builder.append(str.substring(endIndex + 1));
return builder.toString();
}
return null;
}
@Test
public void testReverse() {
String str = "abcdefg";
String reverse = reverse(str, 2, 5);
System.out.println(reverse);
String reverse1 = reverse(str, 2, 5);
System.out.println(reverse1);
String reverse2 = reverse(str, 2, 5);
System.out.println(reverse2);
}
}
java学习之String常用类将字符串指定的部分进行反转
最新推荐文章于 2023-04-26 11:59:14 发布