write a program to check whether a string is palindrome or not
Answers
Following is C implementation to check if a given string is palindrome or not.
// A function to check if a string str is palindrome
void is Palindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters while they are same
while (h > l)
{
if (str[l++] != str[h--])
{
printf("%s is Not Palindrome", str);
return;
}
}
printf("%s is palindrome", str);
}
// Driver program to test above function
int main()
{
isPalindrome("abba");
isPalindrome("abbccbba");
isPalindrome("comp");
return 0;
}
Output:
abba is palindrome
abbccbba is palindrome
comp is Not Palindrome
s = input("Enter a string: ")
if s[0:] == s[::-1]:
print("The string is a palindrome.")
else:
print("The string isn't a palindrome.")
The above program can be done using string slicing.
String slicing is the act of extracting a substring from a given string. In order to do so, one must understand how to declare each character's index values.
- Positive indexing starts traversing through the string forwards and starts with the index value 0.
- Negative indexing starts traversing through the string backwards and starts with the index value -1.
When you give a negative number as the step value, the string is read in its reverse order.