String Functions in C

C provides several standard library functions to work with strings. Before moving further, we’ve prepared a video tutorial to understand what String Functions are in C:

Video: String Functions in C

Video: String Functions in C (Hindi)

To work with string functions in the C language, use the following header file:

string.h

Include it in your program file:

#include <string.h>

Let us now see some popular string functions in C language and what they will return after execution:

  1. strlen(): returns the length of a given string
  2. strcmp(): compares two strings
  3. strcpy(): copies one string to another
  4. strcat(): concatenates two strings

Let us see an example implementing all the above string functions:

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

int main() {
    // This initializes a character array str1 with the string "Hello"
    char str1[20] = "Hello";
    /* This declares an empty character array str2 with space for 20 
     characters, but it doesn't initialize it with any value. */
    char str2[20];

    // Copying string
    strcpy(str2, str1);
    printf("str2 after strcpy: %s\n", str2);

    // Concatenating strings
    strcat(str1, ", Amit!");
    printf("str1 after strcat: %s\n", str1);

    // String length
    int len = strlen(str1);
    printf("Length of str1: %d\n", len);

    // Comparing strings
    int result = strcmp(str1, str2);
    if (result == 0) {
        printf("str1 and str2 are equal\n");
    } else {
        printf("str1 and str2 are not equal\n");
    }

    return 0;
}

Output

str2 after strcpy: Hello
str1 after strcat: Hello, Amit!
Length of str1: 12
str1 and str2 are not equal

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

Format Specifiers in C
Storage Classes in C
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment