Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <ctype.h>
- bool is_alpha(char ch) {
- if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90)) {
- return true;
- }
- return false;
- }
- size_t getl(char **lineptr)
- {
- size_t size = 0;
- char ch;
- while ((ch = getchar()) != '\n' && ch != EOF)
- {
- // allocate it if it's not
- if (!*lineptr) {
- *lineptr = (char*)malloc(sizeof(char));
- size = 1;
- }
- else {
- *lineptr = (char*)realloc(*lineptr, ++size);
- }
- // copy
- (*lineptr)[size - 1] = ch;
- }
- // add null termination if the pointer is not null
- if (*lineptr) {
- // realloc with +1 size
- *lineptr = (char*)realloc(*lineptr, ++size);
- (*lineptr)[size - 1] = '\0';
- }
- return size - 1; // don't count null termination
- }
- size_t filter_alphabets(char **target, size_t size) {
- char *result = NULL;
- size_t result_size = 0;
- size_t idx = 0;
- while(idx < size) {
- if(is_alpha((*target)[idx])) {
- if(!result) {
- result = (char*)malloc(sizeof(char));
- result_size = 1;
- }
- else {
- // increase buffer size by one
- result = (char*)realloc(result, ++result_size);
- }
- result[result_size - 1] = tolower((*target)[idx]);
- }
- idx++;
- }
- // add null termination char if result is not null
- if (result) {
- result = (char*)realloc(result, ++result_size);
- result[result_size - 1] = '\0';
- free(*target);
- } else {
- result_size = 1; // fixes negative return thing. I'm so lazy
- }
- *target = result;
- return result_size - 1; // ignore null termination
- }
- bool is_palindrome(char *src, size_t size) {
- size_t i = 0;
- size_t j = size - 1;
- while(i < size) {
- if(src[i] != src[j])
- return false;
- i++;
- j--;
- }
- }
- int main()
- {
- while(1) {
- char *input = NULL;
- size_t size = getl(&input);
- if(!input)
- // input is empty or EOF
- break;
- // remove all non alphabets
- size = filter_alphabets(&input, size);
- if(is_palindrome(input, size))
- printf("Palindrome\n");
- else
- printf("Not Palindrome\n");
- free(input);
- }
- }
Add Comment
Please, Sign In to add comment