判断 字符串 的是否对称。
定义一个 方法 判断字符串是否对称,例如:“abcba”、“上海自来水来自海上” 均为对称字符串。
public class StringBuilderDemo03 {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// 定义三个字符串
String str1 = "abcba";
String str2 = "上海自来水来自海上";
String str3 = "haicoder";
// 调用判断是否对称的方法
Boolean bool1 = Util(str1);
Boolean bool2 = Util(str2);
Boolean bool3 = Util(str3);
// 输出结果
System.out.println(str1 + " 是否对称:" + bool1);
System.out.println(str2 + " 是否对称:" + bool2);
System.out.println(str3 + " 是否对称:" + bool3);
}
public static Boolean Util(String str){
// 创建 StringBuilder 对象
StringBuilder sb = new StringBuilder(str);
// 字符串反转,并将 StringBuilder 对象转为 String 类型
String str2 = sb.reverse().toString();
// 判断是否字符串对称
if(str.equals(str2)){
return true;
}else{
return false;
}
}
}
运行结果如下图:
以上实例实现判断字符串是否对称。