31.
Input and display a string
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str); // use fgets(str, sizeof(str), stdin); in modern C
printf("You entered: %s", str);
return 0;
}
32. Find the length of a string
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Length = %lu", strlen(str));
return 0;
}
33. Copy one string to another
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter a string: ");
gets(str1);
strcpy(str2, str1);
printf("Copied string: %s", str2);
return 0;
}
34. Concatenate two strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
strcat(str1, str2);
printf("Concatenated string: %s", str1);
return 0;
}
35. Compare two strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if (strcmp(str1, str2) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
36. Convert string to uppercase
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
for (int i = 0; str[i]; i++)
str[i] = toupper(str[i]);
printf("Uppercase string: %s", str);
return 0;
}
37. Count vowels in a string
#include <stdio.h>
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
gets(str);
for (int i = 0; str[i]; i++) {
char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
count++;
}
printf("Number of vowels = %d", count);
return 0;
}
38. Reverse a string (without library function)
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
int len = strlen(str);
printf("Reversed string: ");
for (int i = len - 1; i >= 0; i--)
printf("%c", str[i]);
return 0;
}
39. Check if a string is a palindrome
#include <stdio.h>
#include <string.h>
int main() {
char str[100], rev[100];
printf("Enter a string: ");
gets(str);
strcpy(rev, str);
strrev(rev); // or reverse manually if not using Turbo C
if (strcmp(str, rev) == 0)
printf("Palindrome");
else
printf("Not a palindrome");
return 0;
}
40. Count words in a string
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[200];
int count = 0, inWord = 0;
printf("Enter a sentence: ");
gets(str);
for (int i = 0; str[i]; i++) {
if (isspace(str[i])) {
inWord = 0;
} else if (!inWord) {
count++;
inWord = 1;
}
}
printf("Word count = %d", count);
return 0;
}