đ§Ē Check if a String is a Palindrome in C
This tutorial shows you how to check if a string is a palindrome in C. A palindrome is a word or sentence that reads the same forwards and backwards. For example, "madam" or "A man a plan a canal Panama".
We’ll ignore case and spaces while checking. Two versions are shown:
- ✅ Using a separate function
- đ ️ Without using any function
✅ Method 1: With Function (Ignoring Case & Spaces)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void removeSpacesAndToLower(char *src, char *cleaned) {
int j = 0;
for (int i = 0; src[i] != '\0'; i++) {
if (!isspace(src[i])) {
cleaned[j++] = tolower(src[i]);
}
}
cleaned[j] = '\0';
}
int isPalindrome(char *str) {
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
if (str[start] != str[end]) {
return 0; // Not palindrome
}
start++;
end--;
}
return 1; // Palindrome
}
int main() {
char input[100], cleaned[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
removeSpacesAndToLower(input, cleaned);
if (isPalindrome(cleaned)) {
printf("✅ The string is a palindrome.\n");
} else {
printf("❌ The string is NOT a palindrome.\n");
}
return 0;
}
đ§ Explanation:
removeSpacesAndToLower()
cleans the input by removing spaces and converting all letters to lowercase.isPalindrome()
compares the cleaned string from both ends.
đ ️ Method 2: Without Function (All logic inside main()
)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char input[100], cleaned[100];
int i, j = 0;
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
// Remove spaces and convert to lowercase
for (i = 0; input[i] != '\0'; i++) {
if (!isspace(input[i])) {
cleaned[j++] = tolower(input[i]);
}
}
cleaned[j] = '\0';
// Check palindrome
int start = 0, end = strlen(cleaned) - 1;
int is_palindrome = 1;
while (start < end) {
if (cleaned[start] != cleaned[end]) {
is_palindrome = 0;
break;
}
start++;
end--;
}
if (is_palindrome) {
printf("✅ The string is a palindrome.\n");
} else {
printf("❌ The string is NOT a palindrome.\n");
}
return 0;
}
đ Output Examples:
Enter a string: Madam ✅ The string is a palindrome. Enter a string: Hello ❌ The string is NOT a palindrome. Enter a string: A man a plan a canal Panama ✅ The string is a palindrome.
đ Summary
Checking for palindromes in C teaches you about string manipulation, ignoring whitespace, case conversion, and index-based comparison. Practicing both with and without functions builds solid C fundamentals.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ