0
0
Cprogramming~5 mins

String handling using library functions

Choose your learning style9 modes available
Introduction

We use library functions to easily work with text (strings) without writing long code. They help us find length, copy, join, or compare strings quickly.

When you want to find how many characters are in a word or sentence.
When you need to copy one string into another.
When you want to join two strings together.
When you want to check if two strings are the same.
When you want to find a part of a string inside another string.
Syntax
C
#include <string.h>

size_t strlen(const char *str);
char *strcpy(char *dest, const char *src);
char *strcat(char *dest, const char *src);
int strcmp(const char *str1, const char *str2);
char *strstr(const char *haystack, const char *needle);

Always include <string.h> to use these functions.

Strings in C are arrays of characters ending with a special \0 character.

Examples
Finds the length of the string "hello" which is 5.
C
#include <string.h>

size_t length = strlen("hello");
Copies the string "world" into the array dest.
C
char dest[20];
strcpy(dest, "world");
Joins "friend!" to the end of "Hello, ".
C
char str1[20] = "Hello, ";
strcat(str1, "friend!");
Compares two strings; returns 0 if they are the same.
C
int result = strcmp("apple", "apple");
Sample Program

This program shows how to find string length, copy strings, join strings, compare them, and find a substring using library functions.

C
#include <stdio.h>
#include <string.h>

int main() {
    char str1[50] = "Hello";
    char str2[] = " World";
    char str3[50];

    // Find length
    printf("Length of str1: %zu\n", strlen(str1));

    // Copy str1 to str3
    strcpy(str3, str1);
    printf("After copy, str3: %s\n", str3);

    // Concatenate str2 to str1
    strcat(str1, str2);
    printf("After concatenation, str1: %s\n", str1);

    // Compare str1 and str3
    int cmp = strcmp(str1, str3);
    if (cmp == 0) {
        printf("str1 and str3 are the same\n");
    } else {
        printf("str1 and str3 are different\n");
    }

    // Find substring
    char *pos = strstr(str1, "World");
    if (pos != NULL) {
        printf("Found 'World' in str1 at position: %ld\n", (long)(pos - str1));
    } else {
        printf("'World' not found in str1\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Make sure destination arrays are large enough to hold the result to avoid errors.

String functions expect strings to end with \0, so always use proper string initialization.

Comparing strings with strcmp returns 0 if equal, negative if first is smaller, positive if first is larger.

Summary

Library functions make string tasks easy and fast.

Remember to include <string.h> and use proper string arrays.

Common functions: strlen, strcpy, strcat, strcmp, strstr.