String Manipulation
String manipulation refers to the process of performing operations on strings, such as copying,
concatenating, comparing, finding length, reversing, or replacing characters.
In C, strings are represented as arrays of characters terminated by a null character (\0).
Common String Functions in C
1. strlen(str): Finds the length of the string.
2. strcpy(dest, src): Copies one string into another.
3. strcat(dest, src): Concatenates two strings.
4. strcmp(str1, str2): Compares two strings.
5. strrev(str): Reverses a string (available in some compilers like Turbo C).
---
Program: Check if a String is Palindrome
A palindrome is a string that reads the same forward and backward (e.g., "madam", "level").
Code Example
#include <stdio.h>
#include <string.h>
int main() {
char str[100], reversed[100];
int length, isPalindrome = 1;
// Input string
printf("Enter a string: ");
scanf("%s", str);
// Find length of the string
length = strlen(str);
// Reverse the string manually
for (int i = 0; i < length; i++) {
reversed[i] = str[length - i - 1];
}
reversed[length] = '\0'; // Null-terminate the reversed string
// Check if original and reversed strings are the same
for (int i = 0; i < length; i++) {
if (str[i] != reversed[i]) {
isPalindrome = 0; // Not a palindrome
break;
}
}
// Output result
if (isPalindrome) {
printf("The string '%s' is a palindrome.\n", str);
} else {
printf("The string '%s' is not a palindrome.\n", str);
}
return 0;
}
Sample Input and Output
Input:
Enter a string: madam
Output:
The string 'madam' is a palindrome.
Input:
Enter a string: hello
Output:
The string 'hello' is not a palindrome.