写出一个java程序:判断一个字符串是否是对称字符串,例如"abc"不是对称字符串,"aba"、"abba"、"aaa"、"mnanm"是对称字符串,分别使用(String和StringBuffer实现这个功能。
时间: 2023-07-02 16:11:29 浏览: 213
java代码-编写一个程序判断字符串是否在另一个字符串
使用 String 实现:
```java
public class StringSymmetry {
public static boolean isSymmetry(String s) {
int length = s.length();
for (int i = 0; i < length / 2; i++) {
if (s.charAt(i) != s.charAt(length - i - 1)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s1 = "abc";
String s2 = "aba";
String s3 = "abba";
String s4 = "aaa";
String s5 = "mnanm";
System.out.println(s1 + " isSymmetry: " + isSymmetry(s1));
System.out.println(s2 + " isSymmetry: " + isSymmetry(s2));
System.out.println(s3 + " isSymmetry: " + isSymmetry(s3));
System.out.println(s4 + " isSymmetry: " + isSymmetry(s4));
System.out.println(s5 + " isSymmetry: " + isSymmetry(s5));
}
}
```
使用 StringBuffer 实现:
```java
public class StringBufferSymmetry {
public static boolean isSymmetry(String s) {
StringBuffer sb = new StringBuffer(s);
return s.equals(sb.reverse().toString());
}
public static void main(String[] args) {
String s1 = "abc";
String s2 = "aba";
String s3 = "abba";
String s4 = "aaa";
String s5 = "mnanm";
System.out.println(s1 + " isSymmetry: " + isSymmetry(s1));
System.out.println(s2 + " isSymmetry: " + isSymmetry(s2));
System.out.println(s3 + " isSymmetry: " + isSymmetry(s3));
System.out.println(s4 + " isSymmetry: " + isSymmetry(s4));
System.out.println(s5 + " isSymmetry: " + isSymmetry(s5));
}
}
```
阅读全文