How to reverse a string and check Palindrome

Programming

String

A string is a sequence of characters and we can access any character by its index.
So we can treat a string as a 1D array.

Note: Array indexing starts from 0 and it is also common in many programming languages like C, C++, C#, Java, Php, Ruby, Python etc...

String representation as 1D array


+-------------------------+
|Index| 0 | 1 | 2 | 3 | 4 |
+-------------------------+
|Chars| H | e | l | l | o |
+-------------------------+

How to solve

We will use variable str to store the string and tmp to swap characters of the string str


Take a string from user and store it in variable str
Set begin to 0 (first index of the string)
Set end to L (last index of the string)

Swap str[begin] with str[end] till begin < end

Print str to get the required reversed string

Palindrome

If the reverse of a string is equal to the original string then we call it a palindrome.
Palindrome Example: madam

Code in C


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

int main(){
	char str[100], tmp, rev[100];
	int begin, end;
	
	//input
	printf("Enter string: ");
	scanf("%s", &str);
	
	//copy str to rev
	strcpy(rev,str);	//rev will be used to check palindrome
	
	//reverse
	begin = 0;
	end = strlen(str) - 1;	//-1 because last character is NULL \0
	while(begin < end){
		tmp = str[begin];
		str[begin] = str[end];
		str[end] = tmp;
		begin++;
		end--;
	}
	
	//output
	printf("Reverse string: %s\n", str);
	
	//checking palindrome
	if(strcmp(rev,str) == 0)
		printf("%s is palindrome!\n", str);
	else
		printf("%s is not palindrome!\n", str);
		
	return 0;
}