判断字符串是否为回文字符串
2017-04-10 21:49
78 查看
.1、回文的定义:“回文数”就是正读倒读都一样的整数。如奇数个数字:98789,这个数字正读是98789 倒读也是98789。偶数个数字3223也是回文数。字母 abcba 也是回文
package cn.haoge.demo;import java.util.Scanner;
/**
*类说明:判断字符串是否为回文字符串
*作者:HAO
*创建日期:2017-4-10 下午9:11:11
*/
public class Demo3 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入字符串");
String str=sc.next();
// way1(str);
// way2(str);
way3(str);
}
//原字符串与反转之后的字符串进行比较
private static void way3(String str) {
StringBuffer sb=new StringBuffer(str);
sb.reverse();
String newstr=new String(sb);
if(str.equals(newstr)){
System.out.println("字符串为回文字符串");
}else{
System.out.println("字符串不是回文字符串");
}
}
//方式二:将字符串转换为字符数组,截取对称的字符进行比较
private static void way2(String str) {
char[] charArray = str.toCharArray();//将字符串转换为字符数组
boolean istrue=true;
for(int i=0;i<charArray.length/2;i++){
if(charArray[i]!=charArray[charArray.length-i-1]){
istrue=false;
}
}
if(istrue==true){
System.out.println("输入的字符串为回文字符");
}else{
System.out.println("输入的字符串不是回文字符串");
}
}
//方式一:将字符串倒置后逐一进行比较
private static void way1(String str) {
StringBuffer sb=new StringBuffer(str);
sb.reverse();//将字符串进行反转
int count=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)==sb.charAt(i)){//charAt(int i)返回字符串中指定位置的字符
count++;
}
}
if(count==str.length()){
System.out.println("字符串为回文字符串");
}else{
System.out.println("字符串不是回文字符串");
}
}
}
相关文章推荐
- 判断字符串是否是一条回文
- 算法基础——判断一个字符串至多添加一个字符之后是否回文
- 判断一个字符串是否是回文,如果是,返回字符串“yes”,如果不是,返回字符串“no”
- (5) 判断字符串或数字是否是回文的
- 递归法判断字符串是否回文
- java采用3种方式判断用户输入的字符串是否为回文
- C++ 用出入栈判断字符串是否为回文
- 编写函数,判断一个字符串是否是回文
- JS使用栈判断给定字符串是否是回文算法示例
- 队列-----判断一个字符串是否是回文
- 1524 判断输入的字符串是否为回文。
- 判断一个字符串中所有子串是否为回文子串
- 利用顺序栈判断字符串是否回文
- valid-palindrome——判断带符号数字字母的字符串是否为回文
- 第二周 任务七 判断S所指的字符串是否回文
- 判断一个字符串是否回文
- 判断一个字符串是否为回文
- 第十五周OJ——判断字符串是否为回文
- 用栈来判断字符串是否是回文字符串
- 判断字符串是否为”回文“