C - String Manipulation Library Functions

In C, there are several library functions available for string manipulation. These functions allow you to perform various operations on strings, such as copying, concatenating, searching, and comparing strings. Here are some common C string manipulation library functions:

1. strlen - Calculates the length of a string (number of characters):

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

int main() {
    char str[] = "Hello, World!";
    int length = strlen(str);

    printf("Length of the string: %d\n", length);

    return 0;
}

2. strcpy - Copies one string to another:

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

int main() {
    char source[] = "Source String";
    char destination[20];

    strcpy(destination, source);

    printf("Copied string: %s\n", destination);

    return 0;
}

3. strcat - Concatenates (appends) one string to another:

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

int main() {
    char str1[] = "Hello, ";
    char str2[] = "World!";
    char result[30];

    strcpy(result, str1);
    strcat(result, str2);

    printf("Concatenated string: %s\n", result);

    return 0;
}

4. strcmp - Compares two strings lexicographically:

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

int main() {
    char str1[] = "apple";
    char str2[] = "banana";

    int result = strcmp(str1, str2);

    if (result < 0) {
        printf("str1 is less than str2\n");
    } else if (result > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is equal to str2\n");
    }

    return 0;
}

5. strchr - Searches for the first occurrence of a character in a string:

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

int main() {
    char str[] = "Hello, World!";
    char *result = strchr(str, 'W');

    if (result != NULL) {
        printf("Found 'W' at position %ld\n", result - str);
    } else {
        printf("Character not found\n");
    }

    return 0;
}

6. strstr - Searches for the first occurrence of a substring in a string:

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

int main() {
    char str[] = "The quick brown fox";
    char *result = strstr(str, "brown");

    if (result != NULL) {
        printf("Found 'brown' at position %ld\n", result - str);
    } else {
        printf("Substring not found\n");
    }

    return 0;
}

These functions are part of the string.h library and are essential for string manipulation in C programs. They help you work with strings efficiently by performing common tasks like length calculation, copying, concatenation, comparison, and searching.