黑马程序员技术交流社区
标题:
44、判断一个字符串是否是对称字符串
[打印本页]
作者:
knockout
时间:
2015-9-8 22:20
标题:
44、判断一个字符串是否是对称字符串
8. public class Demo44 {
9. public static void main(String[] args){
10. String str = "abc";
11. cmp(str);
12.
13. }
14.
15. public static void cmp(String str) {
16. boolean result = true; //定义默认结果是正确的
17. int count = (str.length()-1)/2; //定义个数,如果是奇数除以 2,int 类型结果还是整数,用于 for 循环比较的次数;
18.
19. for (int x = 0;x <= count ;x++ ){ //循环遍历
20. if(str.charAt(x) != str.charAt(str.length()-1-x)){ //指定索引位置返回的字符值进行比较,如果不相等
21. result = false; //结果为不对称
22. }
23. }
24. if(! result){
25. System.out.println("该字符串是不对称的");
26.
27. }
28. else{
29. System.out.println("该字符串是对称的");
30.
31. }
32. }
33. //方法 2
34. public static boolean isSame(String str) {
35. return new StringBuilder(str).reverse().toString().equals(str);
36. }
37. }
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2