使用Java编写(2)从键盘录入一个字符串,分别使用String和StringBuffer实现字符串的反转
时间: 2024-02-06 10:10:35 浏览: 69
使用String实现字符串反转:
```java
import java.util.Scanner;
public class StringReverse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = scanner.nextLine();
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse += str.charAt(i);
}
System.out.println("反转后的字符串为:" + reverse);
}
}
```
使用StringBuffer实现字符串反转:
```java
import java.util.Scanner;
public class StringBufferReverse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(str);
System.out.println("反转后的字符串为:" + stringBuffer.reverse());
}
}
```
阅读全文