how to check a string is palindrome or not code example
Example 1: check if a string is palindrome cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
int l = 0;
int h = s.length()-1;
while(h > l){
if(s[l++] != s[h--]){
cout << "Not a palindrome" << endl;
return 0;
}
}
cout << "Is a palindrome" << endl;
return 0;
}
Example 2: Write a function that tests whether a string is a palindrome
def palindrome_check(string):
string = list(string)
tmp = []
#remove any spaces
for x in range(0, len(string)):
if(string[x] != " "):
tmp.append(string[x].lower())
#now reverse the string
array1 = []
i = 0
j = len(tmp)-1
while(i < len(tmp)):
array1.append(tmp[j])
i += 1
j -= 1
#check if array1 is equal to the string
counter = 0
for x in range(0, len(tmp)):
if(tmp[x] == array1[x]):
counter += 1
#if the counter is equal to the length of the string then the word
#is the same
if(counter == len(tmp)):
return True
return False
Example 3: check if palindrome
function isPalindrome(str) {
str = str.toLowerCase();
return str === str.split("").reverse().join("");
}
Example 4: reads the string in then determines if the string is a palindrome.
#include <iostream>
using namespace std;
bool isPalindrome(string str)
{
int low = 0;
int high = str.length() - 1;
while (low < high)
{
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
int main()
{
string str = "XYXYX";
if (isPalindrome(str))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}
Example 5: Write a program to check whether inputted string is palindrome or not.
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,n,c=0;
printf("Enter the string : ");
gets(s);
n=strlen(s);
for(i=0;i<n/2;i++)
{
if(s[i]==s[n-i-1])
c++;
}
if(c==i)
printf("string is palindrome");
else
printf("string is not palindrome");
return 0;
}
Example 6: reads the string in then determines if the string is a palindrome.
#include <iostream>
using namespace std;
bool isPalindrome(string str, int low, int high)
{
if (low >= high)
return true;
if (str[low] != str[high])
return false;
return isPalindrome(str, low + 1, high - 1);
}
int main()
{
string str = "XYBYBYX";
int len = str.length();
if (isPalindrome(str, 0, len - 1))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}