C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Arrays and Strings
  5. String Library Functions

String Library Functions

C provides many standard string handling functions in the header.

Thank you for reading this post, don't forget to subscribe!

Common Functions:

FunctionDescription
strlen(str)Returns length of the string (excluding \0)
strcpy(dest, src)Copies string src to dest
strcat(dest, src)Appends src to the end of dest
strcmp(s1, s2)Compares two strings (0 if equal)
strrev(str)Reverses the string (non-standard in some compilers)
strchr(str, ch)Finds first occurrence of character in string
strstr(str, substr)Finds first occurrence of substring

Example Code: String Input, Output and Functions:

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

int main() {
    char str1[50], str2[50];

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Removing newline added by fgets
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    printf("\nLength of first string: %lu\n", strlen(str1));
    printf("Length of second string: %lu\n", strlen(str2));

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

    if (strcmp(str1, str2) == 0)
        printf("Strings are equal\n");
    else
        printf("Strings are not equal\n");

    return 0;
}

How can we help?