Skip to content

Instantly share code, notes, and snippets.

@sphinxid
Last active December 12, 2016 09:24
Show Gist options
  • Save sphinxid/179db1d9dd503f26739a324d93083a4f to your computer and use it in GitHub Desktop.
Save sphinxid/179db1d9dd503f26739a324d93083a4f to your computer and use it in GitHub Desktop.
simple palindrome checker in C
/*
* 2016/12/12
*
* palindrome.c
* Simple palindrome checker for small string. (cAsE sEnsiTivE)
*
* Firman Gautama <[email protected]>
*
*/
#include <stdio.h>
#include <stdlib.h> // for malloc()
#include <string.h> // for strncpy()
int isPalindrome(char *str1);
int main(void) {
char string[] = "akuaauka";
char result[20];
if (isPalindrome(string) > 0) {
strncpy(result,"Palindrome", 10);
}
else {
strncpy(result,"NOT Palindrome", 14);
}
printf("The string: \"%s\" is %s\n", string, result);
return 0;
}
int isPalindrome(char *str1) {
int i=0; // real counter
int n=0; // reverse counter
int len = strlen(str1) - 1;
// check for palindrome
for(i=len;i>=0;i--) {
printf("%c = %c\n", str1[i], str1[n]);
// if first char is not equal last char (and the next one from each side), then exit from loop.
if (str1[i] != str1[n]) {
// false
return -1;
}
n++;
if (len/2 == i) {
// if the string check went through here already, then we should break the loop because it's already in the middle of the string.
// there is no point to continue comparing the characters because the rest of comparation should be the same.
break;
}
}
// true
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment