Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Check Whether a String is Palindrome

$
0
0

Palindrome string is a string that reads the same in both directions, forward and backward. For example, “madam” reads the same from both directions. If you reverse a palindrome string, the reversed string would be the same as the original one. Here we’ll see how to write C program to check whether a string is a palindrome.

Method 1

int is_palindrome(char *str) {
  int len = 0, i = 0;
  if(str == NULL) return 0;

  len = strlen(str);

  for(i = 0; i < len/2; i++) {
    if(str[i] != str[len - i -1]) return 0;
  }

  return 1;
}

The above function, is_palindrome(), returns 1 if the input string is a palindrome, otherwise returns 0. It compares the first character with the last character, second character with second last character and so on. If any comparison fails (not equal), that means the string is not palindrome. It returns 0. If all comparisons pass, it returns 1.

Method 2

As I said earlier, the reverse of a palindrome string would be same as the original one. We can first reverse the string and check whether the original string is equal to the original one.

void reverse_string(char *input, char *output) {
  int len = 0, i = 0;

  if(input == NULL || output == NULL) return;

  len = strlen(input);

  for(i = 0; i < len; i++) {
    output[i] = input[len - i -1];
  }

  output[len] = '\0';
}

int is_palindrome(char *str) {
  char rev[128];

  if (str == NULL) return 0;

  reverse_string(str, rev);

  if(strcmp(str, rev) == 0) return 1;

  return 0;
}

The Complete Program

You can compile and run this program.

#include <stdio.h>
#include <string.h>


int is_palindrome(char *str) {
  int len = 0, i = 0;
  if(str == NULL) return 0;

  len = strlen(str);

  for(i = 0; i < len/2; i++) {
    if(str[i] != str[len - i -1]) return 0;
  }

  return 1;
}

int main(){
  char str[128];

  printf("Enter string: ");
  gets(str);

  if(is_palindrome(str)) {
    printf("\"%s\" is a palindrome.\n", str);
  } else {
    printf("\"%s\" is not a palindrome.\n", str);
  }

  return 0;
}

Output of the above program:

Enter string: step on no pets
"step on no pets" is a palindrome.

Enter string: step on no pet
"step on no pet" is not a palindrome.

The post C Program to Check Whether a String is Palindrome appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>