Java编程中如何反转字符串?
2020-04-26
展开全部
public class StringDemo {
public static void main(String[] args) {
String str = "abcdefgABCDEFG";
// 1. 使用StringBuffer
StringBuffer stringBuffer = new StringBuffer(str);
String stringBufferReversedStr = stringBuffer.reverse().toString();
System.out.println("StringBuffer反转字符串: " + stringBufferReversedStr);
// 2. 使用StringBuilder
StringBuilder stringBuilder = new StringBuilder(str);
String stringBuilderReversedStr = stringBuilder.reverse().toString();
System.out.println("StringBuilder反转字符串: " + stringBuilderReversedStr);
// 3. 使用char[]
char[] chars = str.toCharArray();
for (int start = 0, end = chars.length - 1; start < end; start++, end--) {
char temp = chars[end];
chars[end] = chars[start];
chars[start] = temp;
}
String charReversedStr = new String(chars);
System.out.println("char[] 反序字符串: " + charReversedStr);
}
}
public static void main(String[] args) {
String str = "abcdefgABCDEFG";
// 1. 使用StringBuffer
StringBuffer stringBuffer = new StringBuffer(str);
String stringBufferReversedStr = stringBuffer.reverse().toString();
System.out.println("StringBuffer反转字符串: " + stringBufferReversedStr);
// 2. 使用StringBuilder
StringBuilder stringBuilder = new StringBuilder(str);
String stringBuilderReversedStr = stringBuilder.reverse().toString();
System.out.println("StringBuilder反转字符串: " + stringBuilderReversedStr);
// 3. 使用char[]
char[] chars = str.toCharArray();
for (int start = 0, end = chars.length - 1; start < end; start++, end--) {
char temp = chars[end];
chars[end] = chars[start];
chars[start] = temp;
}
String charReversedStr = new String(chars);
System.out.println("char[] 反序字符串: " + charReversedStr);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询