Program 9
Write functions to implement
string operations such as
compare, concatenate, and find string length. Use the
parameter passing techniques. This program demonstrates
custom implementation of standard string library functions and showcases different parameter
passing methods in C programming.
Algorithm
- String Length Function: Traverse string until '\0' and count characters
- String Compare Function: Compare characters one by one, return ASCII difference
- String Concatenate Function: Find end of first string, append second string
- Input Strings: Read two strings from user using gets() function
- Display Menu: Show options for length, compare, and concatenate operations
- User Choice: Read user's choice for which operation to perform
- Execute Operation: Call appropriate function based on user choice
- Display Results: Show the result of the selected string operation
Flowchart
START
→
Input Strings
→
Display Menu
→
Read Choice
→
Switch Case
→
Call Function
→
Display Result
→
STOP
Code
#include <stdio.h>
// Function to find length of string
int my_strlen(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
// Function to compare two strings
int my_strcmp(char str1[], char str2[]) {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i])
return str1[i] - str2[i];
i++;
}
return str1[i] - str2[i];
}
// Function to concatenate two strings
void my_strcat(char str1[], char str2[]) {
int i = 0, j = 0;
// Find end of str1
while (str1[i] != '\0')
i++;
// Append str2
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0'; // Null terminate
}
int main() {
char str1[100], str2[100];
int choice;
printf("Enter first string: ");
gets(str1); // using gets for simplicity (unsafe in practice)
printf("Enter second string: ");
gets(str2);
printf("\nChoose Operation:\n");
printf("1. Find Length\n");
printf("2. Compare Strings\n");
printf("3. Concatenate Strings\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Length of first string = %d\n", my_strlen(str1));
printf("Length of second string = %d\n", my_strlen(str2));
break;
case 2: {
int cmp = my_strcmp(str1, str2);
if (cmp == 0)
printf("Strings are equal\n");
else if (cmp > 0)
printf("First string is greater\n");
else
printf("Second string is greater\n");
break;
}
case 3:
my_strcat(str1, str2);
printf("Concatenated string = %s\n", str1);
break;
default:
printf("Invalid choice\n");
}
return 0;
}