/**
* @author txd
* @create 2019-12-23-20:59
*/
public class LianXi {
//将一个字符串进行翻转
public String reverse(String str, int startIndex, int endIndex) {
//方式一:先转换为char[]
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;
}
//方式二:使用String的拼接
public String reverse1(String str, int startIndex, int endIndex) {
if (str != null) {
String reverseStr = str.substring(0, startIndex);//abcdef
for (int i = endIndex; i >= startIndex; i--) {
reverseStr += str.charAt(i);
reverseStr += str.substring(endIndex + 1);
return reverseStr;
}
}
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(endIndex + 1);
return builder.toString();
}
return null;
}
}
自己实现一个翻转字符串操作
最新推荐文章于 2021-12-18 20:17:54 发布