如何实现字符串的反转
文章目录
方法一:将字符串转换为字符数组,使用首位指针对数组进行反转
思路:将字符串通过toCharArray()方法转换为字符数组,用首位指针遍历整个数组并进行交换,通过String的构造方法,将字符数组转为字符串
public void TestStringReverse{
public static void reverse(String str){
char[] char = str.toCharArray();
for(int i=0,j=char.length;i<j;i++,j--){
char temp = char[i];
char[i] = char[j];
char[j] = temp;
}
system.out.println(new String(char));
}
}
方法二:将字符串转换为StringBuffer,通过StringBuffer的构造器将String转为StringBuffer,调用StringBuffer的reverse()方法,最后调用StringBuffer的toString方法将StringBuffer转换为String。
public void TestStringReverse{
public static void reverse(Stirng str){
StringBuffer sb = new StringBuffer(str);
StirngBuffer str = sb.reverse();
system.out.println(str.toString);
}
}
public class TestStringBuffer {
public static void main(String[] args) {
String string = "helloWorld";
testStringBuffer(string);
testStringBuffer02(string);
}
//将字符串进行反转
//方法一
public static void testStringBuffer(String str){
char[] chars = str.toCharArray();
for (int i=0,j=chars.length-1;i<j;i++,j--){
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
System.out.println(new String(chars));
}
//方法二
public static void testStringBuffer02(String str){
StringBuffer sb = new StringBuffer(str);
StringBuffer sb1 = sb.reverse();
System.out.println(sb1.toString());
}
}
方法三:使用String的CharAt()方法将string逐个转换为char类型的字符。然后将字符逆序追加到stringBuffer后面,实现倒叙
public static void testStringBuffer03(String str){
StringBuffer sb = new StringBuffer();
for (int i =str.length()-1;i>-1;i--){
char c = str.charAt(i);
sb.append(c);
}
System.out.println(sb.toString());
}
©;
}
System.out.println(sb.toString());
}