STRING OPERATIONS USING BUILT IN FUNCTIONS
AIM:
To write a C program that performs String operations without using built-in functions.
ALGORITHM:
1. Start the program.
2. Declare three-character arrays str1, str2, and str3.
3. Assign "Hello" to str1 and "World" to str2.
4. Find and print the length of str1 using strlen().
5. Copy the contents of str1 into str3 using strcpy() and print it.
6. Join (concatenate) str2 to str1 using strcat() and print the result.
7. Compare str1 and str2 using strcmp() and display whether they are equal, greater, or smaller.
8. Find the length of str2 and print its characters in reverse order using a loop.
9. Use strchr() to find the first occurrence of the character 'o' in str1 and print its position.
10. Use strstr() to find the substring "World" in str1 and print where it starts.
11. Stop the program.
PROGRAM:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World";
char str3[50];
// strlen() - find length of a string
printf("Length of str1: %lu\n", strlen(str1));
// strcpy() - copy string
strcpy(str3, str1);
printf("Copied str3: %s\n", str3);
// strcat() - concatenate strings
strcat(str1, str2);
printf("After concatenation str1: %s\n", str1);
// strcmp() - compare strings
int result = strcmp(str1, str2);
if (result == 0)
printf("str1 and str2 are equal\n");
else if (result > 0)
printf("str1 is greater than str2\n");
else
printf("str1 is smaller than str2\n");
// strrev() - reverse string (available in some compilers like Turbo C)
// For GCC, we can manually reverse
int len = strlen(str2);
printf("Reversed str2: ");
for (int i = len - 1; i >= 0; i--)
printf("%c", str2[i]);
printf("\n");
// strchr() - find first occurrence of a character
char *ch = strchr(str1, 'o');
if (ch != NULL)
printf("First occurrence of 'o' in str1: %ld\n", ch - str1 + 1);
// strstr() - find substring
char *sub = strstr(str1, "World");
if (sub != NULL)
printf("Substring 'World' found at position: %ld\n", sub - str1 + 1);
return 0;
}
OUTPUT:
Length of str1: 5
Copied str3: Hello
After concatenation str1: HelloWorld
str1 is smaller than str2
Reversed str2: dlroW
First occurrence of 'o' in str1: 5
Substring 'World' found at position: 6
RESULT:
Thus, the above program for string operations using built-in functions has been
executed successfully, and the output has been verified.