——- android教育訓練、java教育訓練、期待與您交流! ———-
class StringReverseDemo
{
public static void main(String[] args)
{
//目标字元串
String str1 = "abcdefghijk";
//反轉全部字元串
String str2 = reverseString(str1);
System.out.println(str2);
//反轉指定字元串
String str3 = reverseString(str1,,);//注意:包含頭不包含尾
System.out.println(str3);
}
//反轉指定字元串
public static String reverseString(String str,int start ,int end)
{
//1 字元串轉字元數組
char[] CharArray = str.toCharArray();
//2 指定數組元素反轉
reverseArray(CharArray,start,end);
//3 數組轉字元串
return new String(CharArray);
}
//反轉全部字元串
public static String reverseString(String str)
{
return reverseString(str,,str.length());
}
//指定數組元素反轉
public static void reverseArray(char[] CharArray,int x,int y)
{
//設定頭尾指針
int start = x,end = y-;
//當頭指針小于尾指針時,首尾交換
while(start<end)
swap(CharArray,start++,end--);
}
//數組全部反轉
public static void reverseArray(char[] CharArray)
{
reverseArray(CharArray,,CharArray.length);
}
//數組指定位置互換操作
public static void swap(char[] ch,int x,int y)
{
//設定一個臨時變量,三變量法
char temp = ch[x];
ch[x] = ch[y];
ch[y] = temp;
}
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyM2gDMyQDNyEDMxQDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)