STRING PROGRAMS
1. String Length
Aim:
To find the length of a given string using the strlen() function.
Algorithm:
Start.
Declare a character array.
Read the string from the user.
Find the length using strlen().
Display the length.
Stop.
Program:
#include <stdio.h>
#include <string.h>
void main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("Length = %lu", strlen(str));
2. String Concatenation
Aim:
To concatenate two strings using the strcat() function.
Algorithm:
Start.
Declare two character arrays.
Read both strings.
Concatenate the second string to the first using strcat().
Display the concatenated string.
Stop.
Program:
#include <stdio.h>
#include <string.h>
void main() {
char str1[100], str2[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
strcat(str1, str2);
printf("Concatenated String = %s", str1);
3. String Comparison
Aim:
To compare two strings using the strcmp() function.
Algorithm:
Start.
Declare two character arrays.
Read both strings.
Compare them using strcmp().
If the result is 0, print "Strings are equal"; otherwise print "Strings are not equal".
Stop.
Program:
#include <stdio.h>
#include <string.h>
void main() {
char str1[100], str2[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
if (strcmp(str1, str2) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");
4. Convert String to Uppercase
Aim:
To convert a given string into uppercase using the toupper() function.
Algorithm:
Start.
Declare a character array.
Read the string.
Traverse each character of the string.
Convert each character to uppercase using toupper().
Display the uppercase string.
Stop.
Program:
#include <stdio.h>
#include <ctype.h>
void main() {
char str[100];
int i;
printf("Enter a string: ");
scanf("%s", str);
for (i = 0; str[i] != '\0'; i++) {
str[i] = toupper(str[i]);
}
printf("Uppercase String = %s", str);
5. Convert String to Lowercase
Aim:
To convert a given string into lowercase using the tolower() function.
Algorithm:
Start.
Declare a character array.
Read the string.
Traverse each character of the string.
Convert each character to lowercase using tolower().
Display the lowercase string.
Stop.
Program:
#include <stdio.h>
#include <ctype.h>
void main() {
char str[100];
int i;
printf("Enter a string: ");
scanf("%s", str);
for (i = 0; str[i] != '\0'; i++) {
str[i] = tolower(str[i]);
}
printf("Lowercase String = %s", str);
6. String Copy
Aim:
To copy one string into another using the strcpy() function.
Algorithm:
Start.
Declare two character arrays.
Read the source string.
Copy the source string to the destination using strcpy().
Display the copied string.
Stop.
Program:
#include <stdio.h>
#include <string.h>
void main() {
char str1[100], str2[100];
printf("Enter a string: ");
scanf("%s", str1);
strcpy(str2, str1);
printf("Copied String = %s", str2);