AIM
Understand string Handling in C Program
Theory:
How does C handle strings?
List of string handling functions in C
Q1.
Problem Statement:
Write a C program to demonstrate basic string handling in C program
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[200];
// Input two strings
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0'; // Remove newline character
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = '\0'; // Remove newline character
// String Length
printf("\nLength of first string: %lu\n", strlen(str1));
printf("Length of second string: %lu\n", strlen(str2));
// String Copy
strcpy(str3, str1);
printf("\nCopy of the first string: %s\n", str3);
// String Concatenation
strcat(str3, str2);
printf("Concatenation of both strings: %s\n", str3);
// String Comparison
int result = strcmp(str1, str2);
if (result == 0) {
printf("\nThe strings are equal.\n");
} else if (result < 0) {
printf("\nThe first string is lexicographically smaller than the second.\n");
} else {
printf("\nThe first string is lexicographically greater than the second.\n");
}
return 0;
}
Q2.
Problem Statement:
Write a program that counts the number of vowels in a given string.
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int i, vowels = 0;
printf("Enter the string: ");
scanf("%[^\n]s",&str);
for(i = 0; str[i]; i++)
{
//Counting the vowels.
if(str[i]=='a'|| str[i]=='e'||str[i]=='i'||
str[i]=='o'|| str[i]=='u'||str[i]=='A'||
str[i]=='E'||str[i]=='I'||str[i]=='O' ||str[i]=='U')
{
vowels++;
}
}
//Printing the count of vowels.
printf("Total number of vowels: = %d\n",vowels);
return 0;
}
Q3.
Problem Statement:
Develop a program to check if a string is a palindrome.
#include <stdio.h>
#include <string.h>
int main() {
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: ");
scanf("%s", string1);
length = strlen(string1);
// Compare characters from the start and end of the string
// and stop if a mismatch is found or the middle of the string is reached.
for (i = 0; i < length / 2; i++) {
if (string1[i] != string1[length - i - 1]) {
flag = 1;
break;
// Output the result
if (flag) {
printf("%s is not a palindrome\n", string1);
} else {
printf("%s is a palindrome\n", string1);
return 0;