📚 C Programming Tutorial

C Programming

Learn C programming concepts with simple explanations, examples and practical notes.

← Back to C Programming

String Library Functions

What are string library functions in C?

In C, string library functions are predefined functions used to perform operations on strings, such as finding their length, copying, joining, comparing, searching, and modifying character sequences.

These functions are declared mainly in the standard header file:

#include <string.h>

A C string is a character sequence terminated by the null character '\0'.

For example:

char name[] = "Naveen";

The array stores N, a, v, e, e, n and '\0'.

List of string library functions in C

The following list covers the commonly taught functions and other important functions declared in <string.h>. Some functions are extensions provided by particular compilers or platforms, rather than standard C functions.

A. Commonly used standard string functions

No. Function Purpose
1 strlen() Finds the length of a string
2 strcpy() Copies a string
3 strncpy() Copies up to a specified number of characters
4 strcat() Appends one string to another
5 strncat() Appends up to a specified number of characters
6 strcmp() Compares two strings
7 strncmp() Compares up to a specified number of characters
8 strchr() Finds the first occurrence of a character
9 strrchr() Finds the last occurrence of a character
10 strstr() Finds the first occurrence of a substring
11 strtok() Splits a string into tokens
12 strspn() Counts initial characters belonging to a specified set
13 strcspn() Counts initial characters not belonging to a specified set
14 strpbrk() Finds the first character matching any character in a set

B. Other standard functions declared in <string.h>

Function Purpose
memcpy() Copies a specified number of bytes between memory regions that do not overlap
memmove() Copies a specified number of bytes and safely handles overlapping regions
memcmp() Compares two memory regions byte by byte
memchr() Searches memory for a byte
memset() Fills a memory region with a specified byte
strcoll() Compares strings according to the current locale's collation rules
strxfrm() Transforms a string for locale-sensitive comparison
strerror() Returns a string describing an error code

The mem... functions operate on memory bytes rather than specifically on null-terminated strings, but they are declared in <string.h> and are often taught alongside string functions.

C. C23 addition

  • memccpy() — added to the C23 standard; copies bytes until a specified byte is copied or a limit is reached.

D. Common compiler-specific or non-standard functions

Function Typical purpose Status
strrev() Reverses a string Not standard C
strupr() Converts a string to uppercase Not standard C
strlwr() Converts a string to lowercase Not standard C
strcasecmp() Compares strings ignoring case POSIX, not ISO C
strdup() Creates a dynamically allocated duplicate of a string POSIX; also standardized in C23

Important: The availability of non-standard functions depends on the compiler or platform. For portable C programs, prefer standard functions or write your own logic when a required operation has no standard string function.

Detailed explanation of string library functions

The examples below use standard C functions. Unless otherwise stated, include #include <stdio.h> and #include <string.h> where required.

strlen() — Finding string length

Purpose: Returns the number of characters in a string, excluding the terminating '\0'.

Syntax:

strlen(string);

Example:

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

int main(void)
{
    char str[] = "Computer";

    printf("Length = %zu\n", strlen(str));

    return 0;
}

Output:

Length = 8

Explanation: Computer contains eight characters. The null character is not counted. The return type is size_t, so %zu is the appropriate printf() format specifier.

strcpy() — Copying a string

Purpose: Copies the source string, including its terminating null character, into the destination.

Syntax:

strcpy(destination, source);

Example:

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

int main(void)
{
    char source[] = "Hello";
    char destination[20];

    strcpy(destination, source);

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

    return 0;
}

Output:

Copied string = Hello

Explanation: Every character from source, including '\0', is copied to destination.

Important: The destination must have enough space. strcpy() does not check the destination's capacity.

strncpy() — Copying a limited number of characters

Purpose: Copies at most a specified number of characters from the source.

Syntax:

strncpy(destination, source, n);

Example:

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

int main(void)
{
    char source[] = "Programming";
    char destination[20];

    strncpy(destination, source, 4);
    destination[4] = '\0';

    printf("%s\n", destination);

    return 0;
}

Output:

Prog

Explanation: The first four characters are copied. We explicitly add '\0' to terminate the destination.

Exam point: Unlike strcpy(), strncpy() does not always append a null character. If the source length is at least n, the destination may not be null-terminated.

strcat() — Concatenating strings

Purpose: Appends the source string to the end of the destination string.

Syntax:

strcat(destination, source);

Example:

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

int main(void)
{
    char first[30] = "Hello ";
    char second[] = "World";

    strcat(first, second);

    printf("%s\n", first);

    return 0;
}

Output:

Hello World

Explanation: strcat() finds the end of first, overwrites its terminating null character with the first character of second, and appends the remaining characters and final null character.

The destination must have enough capacity for both strings and the final '\0'.

strncat() — Concatenating a limited number of characters

Purpose: Appends at most n characters from the source string.

Syntax:

strncat(destination, source, n);

Example:

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

int main(void)
{
    char first[30] = "Good ";
    char second[] = "Morning";

    strncat(first, second, 3);

    printf("%s\n", first);

    return 0;
}

Output:

Good Mor

Explanation: Only the first three characters, Mor, are appended. strncat() also writes a terminating null character. Ensure the destination has sufficient remaining space.

strcmp() — Comparing two strings

Purpose: Compares two strings lexicographically, character by character.

Syntax:

strcmp(string1, string2);

Return value:
- A value less than zero if the first string compares less than the second.
- 0 if both strings are equal.
- A value greater than zero if the first string compares greater than the second.

Example:

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

int main(void)
{
    char a[] = "Apple";
    char b[] = "Apple";
    char c[] = "Banana";

    printf("%d\n", strcmp(a, b));
    printf("%d\n", strcmp(a, c));

    return 0;
}

Output:

0
-1

The second result is negative because "Apple" compares before "Banana" in the execution character set. The exact nonzero value returned by strcmp() is not guaranteed to be -1 or 1; only its sign matters.

strncmp() — Comparing a limited number of characters

Purpose: Compares at most the first n characters of two strings.

Syntax:

strncmp(string1, string2, n);

Example:

strncmp("Computer", "Comrade", 3);  /* Returns 0 */
strncmp("Computer", "Comrade", 4);  /* Returns a negative value */

Explanation: The first three characters, Com, match in both strings, so comparing three characters returns 0. The fourth characters, p and r, differ, so comparing four characters returns a negative value because p comes before r.

strchr() — Searching for the first occurrence of a character

Purpose: Finds the first occurrence of a specified character in a string.

Syntax:

strchr(string, character);

Example:

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

int main(void)
{
    char str[] = "programming";
    char *p = strchr(str, 'm');

    if (p != NULL)
        printf("%s\n", p);

    return 0;
}

Output:

mming

Explanation: strchr() returns a pointer to the first 'm'. Printing that pointer using %s displays the string starting from that position. It returns NULL if the character is not found.

strrchr() — Searching for the last occurrence of a character

Purpose: Finds the last occurrence of a specified character.

Syntax:

strrchr(string, character);

Example:

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

int main(void)
{
    char str[] = "programming";
    char *p = strrchr(str, 'm');

    if (p != NULL)
        printf("%s\n", p);

    return 0;
}

Output:

ming

Explanation: The last 'm' occurs before i, so the returned pointer refers to the substring "ming".

strstr() — Searching for a substring

Purpose: Finds the first occurrence of one string inside another string.

Syntax:

strstr(main_string, substring);

Example:

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

int main(void)
{
    char str[] = "C programming language";
    char *p = strstr(str, "programming");

    if (p != NULL)
        printf("%s\n", p);
    else
        printf("Substring not found\n");

    return 0;
}

Output:

programming language

Explanation: The returned pointer points to the first character of the matching substring. If the substring is not found, the function returns NULL. An empty substring matches at the beginning of the main string.

strtok() — Splitting a string into tokens

Purpose: Splits a string into smaller pieces called tokens, using delimiter characters.

Syntax:

strtok(string, delimiters);

Example:

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

int main(void)
{
    char str[] = "C,Java,Python";
    char *token = strtok(str, ",");

    while (token != NULL)
    {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }

    return 0;
}

Output:

C
Java
Python

Explanation:

  1. The first call supplies the string to tokenize.
  2. Each later call uses NULL to continue processing the same string.
  3. The delimiter comma separates the tokens.

Important: strtok() modifies the original character array by replacing delimiters with '\0'. Do not pass a string literal to it. It also maintains internal state, so be careful when tokenizing multiple strings in nested or interleaved operations.

strspn() — Counting initial characters from a set

Purpose: Returns the length of the initial part of a string containing only characters found in a specified set.

Syntax:

strspn(string, accepted_characters);

Example:

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

int main(void)
{
    char str[] = "12345ABC";
    printf("%zu\n", strspn(str, "0123456789"));

    return 0;
}

Output:

5

Explanation: The first five characters are digits. The function stops at A, which is not in the accepted set.

strcspn() — Counting initial characters not from a set

Purpose: Returns the length of the initial part of a string that contains none of the characters in a specified set.

Syntax:

strcspn(string, rejected_characters);

Example:

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

int main(void)
{
    char str[] = "hello,world";
    printf("%zu\n", strcspn(str, ","));

    return 0;
}

Output:

5

Explanation: Five characters (hello) occur before the comma, which belongs to the rejected set.

strpbrk() — Searching for any character from a set

Purpose: Finds the first character in a string that matches any character in a specified set.

Syntax:

strpbrk(string, character_set);

Example:

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

int main(void)
{
    char str[] = "Computer Science";
    char *p = strpbrk(str, "aeiou");

    if (p != NULL)
        printf("%s\n", p);

    return 0;
}

Output:

omputer Science

Explanation: The first vowel encountered is o, so the returned pointer refers to "omputer Science".

strcoll() — Locale-sensitive string comparison

Purpose: Compares two strings according to the collation rules of the current locale.

Syntax:

strcoll(string1, string2);

Example:

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

int main(void)
{
    int result = strcoll("apple", "banana");

    if (result == 0)
        printf("Equivalent in collation\n");
    else if (result < 0)
        printf("First comes before second\n");
    else
        printf("First comes after second\n");

    return 0;
}

The output depends on the active locale's collation rules. In a typical default locale, the first string comes before the second.

strxfrm() — Transforming a string for locale-sensitive comparison

Purpose: Transforms a string into a form that can be compared using strcmp() to obtain ordering equivalent to strcoll() for the same locale.

Syntax:

strxfrm(destination, source, n);

This function is more advanced and is used when locale-sensitive comparisons need to be performed repeatedly. The destination must be handled carefully because the transformed representation can require more space than the original string.

strerror() — Getting an error message

Purpose: Returns a string describing a specified error code.

Syntax:

strerror(error_number);

Example:

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

int main(void)
{
    printf("%s\n", strerror(ENOENT));
    return 0;
}

ENOENT commonly represents a missing file or directory. The exact message depends on the implementation and locale.

Memory functions from <string.h>

These functions are not limited to strings. They operate on a specified number of bytes, so they are useful when working with character arrays and other memory regions.

Function Purpose Example
memcpy() Copies bytes; source and destination must not overlap memcpy(dest, src, 5);
memmove() Copies bytes safely even when regions overlap memmove(dest, src, 5);
memcmp() Compares two blocks of bytes memcmp(a, b, 5);
memchr() Searches a memory block for a byte memchr(buf, 'A', 10);
memset() Fills a memory block with a byte value memset(buf, 0, sizeof buf);
memccpy() Copies bytes until a specified byte is copied or a limit is reached; available in C23 memccpy(dest, src, '\n', n);

Example: memset()

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

int main(void)
{
    char str[6];

    memset(str, 'A', 5);
    str[5] = '\0';

    printf("%s\n", str);

    return 0;
}

Output:

AAAAA

Note that memset() fills bytes. It does not automatically create a valid null-terminated string unless you ensure the array contains a terminating '\0'.

Non-standard functions commonly found in textbooks

Some older compilers and teaching environments provide functions such as:

  • strrev() — reverses a string.
  • strupr() — converts a string to uppercase.
  • strlwr() — converts a string to lowercase.

These are not standard ISO C functions. They may work in certain compilers but fail to compile in others. You can implement their behavior manually or use portable character functions from <ctype.h>.