C++实现判断字符串是否回文实例解析
本文实例解析了C++判断字符串是否回文的实现过程,通过数据结构中的相关例子,回文判断中采用过滤空格字符、有效字符依次入栈等方法实现该功能。
具体实例代码如下:
#include <iostream> using namespace std; #define Max_String_Len 100 #include "SqStack.h" //判断字符串是否回文 bool ispalindrome(char *in_string) { SqStack <char> s(Max_String_Len); char deblankstring[Max_String_Len], c; int i = 0; //过滤空格字符 while(*in_string != '\0'){ if(*in_string != ' ') deblankstring[i++] = *in_string; in_string++; } deblankstring[i] = '\0'; //有效字符依次入栈 i = 0; while(deblankstring[i] != '\0') s.Push(deblankstring[i++]); //从栈中弹出字符依次比较 i = 0; while(!s.Empty()){ c = s.Top(); s.Pop(); if(c != deblankstring[i]) return false; i++; } return true; } int main() { char instring[Max_String_Len]; cout << "input a string:" << endl; cin.get(instring, Max_String_Len); //cout<<instring; if(ispalindrome(instring)) cout << "\"" << instring << "\"" << " is a palindrome." << endl; else cout << "\"" << instring << "\"" << " is not a palindrome." << endl; system("pause"); return 0; }
赞 (0)