Skip to content
StudyFame

String Functions in C (string.h)

You can't copy a string with = or compare two strings with == in C. For these jobs, C gives you ready-made functions in the header file string.h.

In this lesson you will learn the most used string functions: strlen, strcpy, strcat, strcmp, plus a few useful extras. These four are asked in nearly every C exam and viva.

What You Will Learn

  • What string.h is.
  • How to find length with strlen.
  • How to copy with strcpy and strncpy.
  • How to join strings with strcat.
  • How to compare strings with strcmp and read its return value.
  • How to search with strchr and strstr.

String Library Functions in C (string.h)

Exam definition: String handling functions are predefined functions declared in the header file <string.h> that perform common operations on strings, such as finding length (strlen), copying (strcpy), joining (strcat) and comparing (strcmp).

Memory trick: Read the names aloud: str + length, str + copy, str + concatenate, str + compare. For copy and cat, the order is like =: destination first, source second (dest = src).

Syntax of Common String Functions

FunctionWhat it doesReturns
strlen(s)Counts characters before '\0'Length (size_t)
strcpy(dest, src)Copies src into dest (with '\0')dest
strncpy(dest, src, n)Copies at most n charactersdest
strcat(dest, src)Adds src to the end of destdest
strncat(dest, src, n)Adds at most n characters of srcdest
strcmp(s1, s2)Compares character by character0 if equal; < 0 or > 0 otherwise
strchr(s, c)Finds first character cPointer to it, or NULL
strstr(s, sub)Finds substring subPointer to it, or NULL

strrev, strupr and strlwr appear in old Turbo C books, but they are not standard C. GCC doesn't have them. You will write your own in the next lesson.

Example 1: strlen, strcpy and strcat

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

int main(void)
{
    char first[30] = "Virat";
    char last[] = "Kohli";
    char full[30];

    printf("Length of first: %zu\n", strlen(first));
    printf("Array size     : %zu\n", sizeof(first));

    strcpy(full, first);      /* full = "Virat" */
    strcat(full, " ");        /* full = "Virat " */
    strcat(full, last);       /* full = "Virat Kohli" */

    printf("Full name      : %s\n", full);
    printf("Full length    : %zu\n", strlen(full));

    return 0;
}

Output

Length of first: 5
Array size     : 30
Full name      : Virat Kohli
Full length    : 11

Code Explanation

  1. #include <string.h> brings in the declarations of all string functions.
  2. strlen(first) counts letters up to '\0': 5. sizeof(first) is the array size: 30. They are different things.
  3. strcpy(full, first) copies "Virat" and its '\0' into full. Destination comes first.
  4. strcat(full, " ") finds the '\0' of full, writes the space there, and puts a new '\0' after it.
  5. The final length is 5 + 1 + 5 = 11. full must be big enough for 12 bytes.

Practice: concatenate two strings in C and find the length of characters in a string.

How strcmp Works

strcmp compares the strings character by character using ASCII values. It stops at the first difference (or when both end).

strcmp("apple", "apply")
  a = a, p = p, p = p, l = l, e vs y  -> 'e'(101) < 'y'(121)  -> negative

strcmp("Zoo", "apple")
  'Z'(90) vs 'a'(97)                  -> 90 < 97             -> negative
  (capital letters come BEFORE small letters in ASCII)
Result of strcmp(s1, s2)Meaning
0s1 and s2 are equal
< 0s1 comes before s2 (dictionary order)
> 0s1 comes after s2

The exact non-zero number depends on the compiler, so always test with == 0, < 0 or > 0, never with == -1.

Example 2: Password Check and Searching with strcmp, strchr, strstr

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

int main(void)
{
    char saved[] = "india@123";
    char typed[] = "india@123";
    char email[] = "[email protected]";
    char *at, *found;

    if (strcmp(saved, typed) == 0)
        printf("Password correct\n");
    else
        printf("Wrong password\n");

    if (strcmp("Zoo", "apple") < 0)
        printf("\"Zoo\" comes before \"apple\" in ASCII order\n");

    at = strchr(email, '@');
    if (at != NULL)
        printf("Domain: %s\n", at + 1);

    found = strstr(email, "fame");
    if (found != NULL)
        printf("\"fame\" found at index %d\n", (int)(found - email));

    return 0;
}

Output

Password correct
"Zoo" comes before "apple" in ASCII order
Domain: studyfame.com
"fame" found at index 13
  • strcmp(saved, typed) == 0 is the correct way to check equal strings. saved == typed compares addresses, which are never equal for two arrays.
  • strchr returns a pointer to the '@'. at + 1 points to the next character, so printing it shows the domain.
  • found - email subtracts two addresses and gives the index where "fame" starts.
  • Always check for NULL before using the result of strchr/strstr.

Safe Versions: strncpy and strncat

strcpy and strcat don't check if the destination is big enough. The n versions limit how much is copied:

char small[6];
strncpy(small, "Bangalore", sizeof(small) - 1);  /* copies "Banga" */
small[sizeof(small) - 1] = '\0';                  /* strncpy may not add '\0' */

strncpy does not add '\0' if the source is too long, so add it yourself.

Important Points to Remember

  • Include <string.h> to use string functions.
  • strlen doesn't count '\0'; sizeof gives the array size.
  • strcpy/strcat: destination first, and it must be big enough.
  • Compare strings with strcmp(...) == 0, never with ==.
  • strcmp returns 0, negative or positive.
  • strrev, strupr, strlwr are not standard C.

Common Mistakes Beginners Make

MistakeWhat happensFix
if (s1 == s2)Compares addresses: always falseif (strcmp(s1, s2) == 0)
if (strcmp(s1, s2)) to test equalityTrue when they are differentWrite == 0 clearly
strcpy(src, dest) (order swapped)Overwrites your sourceDestination first
Destination too small for strcatBuffer overflow, crashSize ≥ len1 + len2 + 1
Forgetting #include <string.h>Implicit declaration warning/errorInclude the header

String Functions Practice Questions

  1. What is the output of strlen("Hello World")?
  2. What does strcmp return if both strings are equal?
  3. Why can't we compare strings using ==?
  4. What is the minimum size of dest for strcpy(dest, "C Lang")?
  5. Is strrev a standard C function?
Show answers
  1. 11 (the space counts).
  2. 0.
  3. == compares the addresses of the two arrays, not their characters.
  4. 7 bytes (6 characters + '\0').
  5. No. It exists only in some old compilers like Turbo C.

Coding Exercise

Using strcmp, find which of the three names "Meera", "Aman", "Kiran" comes first in dictionary order, then print a greeting made with strcpy and strcat: "Welcome, Aman".

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

int main(void)
{
    char a[] = "Meera", b[] = "Aman", c[] = "Kiran";
    char first[10], msg[30];

    strcpy(first, a);
    if (strcmp(b, first) < 0)
        strcpy(first, b);
    if (strcmp(c, first) < 0)
        strcpy(first, c);

    strcpy(msg, "Welcome, ");
    strcat(msg, first);
    printf("%s\n", msg);
    return 0;
}
Welcome, Aman

Quick Quiz: String Functions in C (MCQ)

  1. Header file for string functions:

    A) stdio.h   B) string.h   C) stdlib.h   D) ctype.h

  2. strlen("C\0Lang") returns:

    A) 6   B) 5   C) 1   D) 0

  3. strcmp("abc", "abd") returns:

    A) 0   B) A positive value   C) A negative value   D) 1 always

  4. Which joins two strings?

    A) strcpy   B) strcat   C) strcmp   D) strlen

  5. In strcpy(a, b), the data is copied:

    A) From a to b   B) From b to a   C) Both ways   D) Nowhere

Show answers
  1. B: string.h.
  2. C: 1 (it stops at the first '\0').
  3. C: negative ('c' < 'd').
  4. B: strcat.
  5. B: from b to a.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Header<string.h>
strlenLength, without '\0'
strcpy(d, s)Copy s into d: destination first
strcat(d, s)Append s to end of d
strcmp = 0Strings equal
strcmp < 0 / > 0s1 before / after s2
Not standardstrrev, strupr, strlwr

Frequently asked questions

What is the difference between strlen and sizeof?
strlen counts characters before '\0' at run time; sizeof gives the whole array size in bytes.
How do you compare two strings in C?
Use strcmp(s1, s2) == 0; == only compares addresses.
What does strcmp return?
0 if equal, negative if s1 comes first, positive if s1 comes later.

Remember

  • len, copy, cat, cmp: the big four.
  • Copy and cat work like dest = src.

Next Topic

Next lesson: String Operations Without string.h. You will write your own strlen, strcpy, strcat, reverse and palindrome check without string.h.