C programming - standard library string.h

‮.www‬theitroad.com

The "string.h" header file in C programming provides functions for manipulating strings, including copying, concatenating, comparing, and searching.

Some of the commonly used functions in "string.h" include:

  1. "strcpy": Copies a string from one location to another.

  2. "strncpy": Copies a specified number of characters from one string to another.

  3. "strcat": Concatenates two strings.

  4. "strncat": Concatenates a specified number of characters from one string to another.

  5. "strcmp": Compares two strings lexicographically.

  6. "strncmp": Compares a specified number of characters from two strings lexicographically.

  7. "strlen": Returns the length of a string.

  8. "strstr": Finds the first occurrence of a substring within a string.

  9. "strchr": Finds the first occurrence of a character in a string.

  10. "strtok": Splits a string into tokens based on a delimiter.

Here is an example of using the "string.h" header file in a C program:

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

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char buffer[100];

    // copy str1 to buffer
    strcpy(buffer, str1);
    printf("Buffer after copying str1: %s\n", buffer);

    // concatenate str2 to buffer
    strcat(buffer, str2);
    printf("Buffer after concatenating str2: %s\n", buffer);

    // compare str1 and str2
    int cmp = strcmp(str1, str2);
    if (cmp < 0) {
        printf("str1 is less than str2\n");
    } else if (cmp > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is equal to str2\n");
    }

    // find the length of buffer
    int len = strlen(buffer);
    printf("Length of buffer: %d\n", len);

    // find the first occurrence of 'o' in buffer
    char *ptr = strchr(buffer, 'o');
    printf("First occurrence of 'o': %s\n", ptr);

    // split buffer into tokens based on spaces
    char *token = strtok(buffer, " ");
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " ");
    }

    return 0;
}

In this example, the "string.h" header file functions are used to manipulate strings. The "strcpy" function is used to copy the string "Hello" to the buffer, and the "strcat" function is used to concatenate the string "World" to the buffer. The "strcmp" function is used to compare the strings "Hello" and "World". The "strlen" function is used to find the length of the buffer. The "strchr" function is used to find the first occurrence of the character 'o' in the buffer. Finally, the "strtok" function is used to split the buffer into tokens based on spaces. The output of the program will be:

Buffer after copying str1: Hello
Buffer after concatenating str2: HelloWorld
str1 is less than str2
Length of buffer: 10
First occurrence of 'o': oWorld
HelloWorld