Complete Guide on String Functions in C

Published: 12 Dec 2025 | Reading Time: 5 min read

Table of Contents

What This Blog Covers

This comprehensive guide provides detailed coverage of string functions in C programming:

Introduction

Handling strings in C can be quite confusing at times as C does not provide a built-in string type as modern languages do. Therefore, students need to deal with character arrays and memory directly, which is a difficult task for beginners.

If you have ever faced segmentation faults, unexpected outputs, or confusing errors while handling text, you're experiencing what most C learners struggle with: understanding how strings actually work behind the scenes.

This blog demystifies handling string functions in C with updated explanations, practical examples, and essential functions. By the end, you'll write safer, cleaner, and more confident C programs.

What are String Functions in C?

C string handling functions are built-in tools that help you work with text (called strings). These functions are available through a special file called <string.h>, which you include at the beginning of your code. Instead of writing long blocks of code to handle string tasks, you can use these ready-made functions to save time and keep your code clean.

Common String Operations

Some common things you can do with string functions include:

String Declaration and Initialization in C

Strings are not specified as a built-in data type in the C programming language. Rather, a string is expressed as an array of characters containing a null character ('\0') at the end. By marking the end of the sequence with this null terminator, C is able to handle the collection of characters as a legitimate string. For text to be handled, stored, and manipulated reliably, proper declaration and initialization are necessary.

1. Declaring Strings in C

Most commonly a string is declared with the help of a character array:

char str[size];

Each element stores a character, and the final position is reserved for the null code unit ('\0'). This structure forms what is known as a null-terminated string.

Fixed-Size Declaration

char greeting[6] = "Hello";

Even though there are five characters in the word "Hello", the array has to allocate one more place for the null terminator.

Implicit Size Declaration

char greeting[] = "Hello";

In this case, the compiler determines the size automatically based on the string literal, including the null character.

2. Initializing Strings

C supports several forms of string initialization, depending on whether the programmer uses string literals, character arrays, or pointers.

Direct Initialization Using a String Literal

char name[] = "John";

The compiler stores the characters followed by '\0'.

Character-by-Character Initialization

char name[] = {'J', 'o', 'h', 'n', '\0'};

This method gives you manual control over each character, and it is also very clear that the null terminator is inserted explicitly.

Initialization Using a Pointer

char *str = "Hello";

In this case, str is pointing to a string literal, which is stored in the memory that is read-only. If you try to change this memory, the result will be undefined behavior, so it is advisable that only character arrays should be used if you want to make changes.

3. Accessing Characters in a String

Strings can be accessed either through array indexing or pointer arithmetic.

Access via Array Indexing

char language[] = "C Language";
printf("%c", language[0]); // Output: C

Access via Pointers

char *ptr = "C Language";
printf("%c", *ptr); // Output: C

Pointers are often used in situations of memory that is dynamically allocated and operations that are performed on strings.

Syntax, Parameters, and Return Values of String Functions in C

Understanding the exact syntax, parameter types, and return values of C string functions is essential for writing correct and efficient code. Below is a reference guide for the most important string functions provided by the <string.h> library and related headers.

strlen - String Length Function

Syntax:

size_t strlen(const char *str);

Parameters:

Returns:

strcpy - String Copy Function

Syntax:

char *strcpy(char *destination, const char *source);

Parameters:

Returns:

strncpy - String N Copy Function

Syntax:

char *strncpy(char *destination, const char *source, size_t n);

Parameters:

Returns:

strcat - String Concatenation Function

Syntax:

char *strcat(char *destination, const char *source);

Parameters:

Returns:

strncat - String N Concatenation Function

Syntax:

char *strncat(char *destination, const char *source, size_t n);

Parameters:

Returns:

strcmp - String Comparison Function

Syntax:

int strcmp(const char *str1, const char *str2);

Parameters:

Returns:

strncmp - String N Comparison Function

Syntax:

int strncmp(const char *str1, const char *str2, size_t n);

Parameters:

Returns:

strchr - String Character Search Function

Syntax:

char *strchr(const char *str, int ch);

Parameters:

Returns:

strrchr - String Reverse Character Search Function

Syntax:

char *strrchr(const char *str, int ch);

Parameters:

Returns:

strstr - String Substring Search Function

Syntax:

char *strstr(const char *haystack, const char *needle);

Parameters:

Returns:

sprintf - String Print Formatted Function

Syntax:

int sprintf(char *str, const char *format, ...);

Parameters:

Returns:

strcspn - String Complement Span Function

Syntax:

size_t strcspn(const char *str1, const char *str2);

Parameters:

Returns:

strset - String Set Function (Non-Standard)

Syntax:

char *strset(char *str, int ch);

Parameters:

Returns:

Note: Non-standard function, may not be available on all systems.

strtod, strtof, strtold - String to Double/Float/Long Double Conversion

Syntax:

double strtod(const char *str, char **endptr);
float strtof(const char *str, char **endptr);
long double strtold(const char *str, char **endptr);

Parameters:

Returns:

Tip: It is always a good idea to check the documentation of your compiler or platform when you are using non-standard functions like strset, strlwr, or strupr.

Common String Functions in C

Let's go through 12 important string functions in C, starting with an easy one. We'll cover what each function does, how to use it, and show simple examples.

1. strlen() - To Find the Length of a String

strlen function in C calculates how many characters are in a string, not counting the null terminator (\0) at the end.

Syntax:

size_t strlen(const char *str);

Example:

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

int main() {
    char message[] = "Hello, world!";
    int length = strlen(message);
    printf("The string length is: %d\n", length);
    return 0;
}

Output:

The string length is: 13

2. strcpy() - Copy One String to Another

strcpy function in C copies the content from one string (source) to another string (destination).

Syntax:

char *strcpy(char *destination, const char *source);

Example:

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

int main() {
    char source[] = "Learning C";
    char destination[50];  // Make sure this is big enough
    strcpy(destination, source);
    printf("Copied string: %s\n", destination);
    return 0;
}

Output:

Copied string: Learning C

3. strcmp() - Compare Two Strings

strcmp function in C is used to compare two strings character by character. It checks the strings in dictionary (lexicographic) order.

Syntax:

int strcmp(const char *str1, const char *str2);

Example:

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

int main() {
    char word1[] = "apple";
    char word2[] = "banana";

    int compare = strcmp(word1, word2);

    if (compare == 0) {
        printf("Both words are the same.\n");
    } else if (compare < 0) {
        printf("\"%s\" comes before \"%s\".\n", word1, word2);
    } else {
        printf("\"%s\" comes after \"%s\".\n", word1, word2);
    }

    return 0;
}

Output:

"apple" comes before "banana".

4. strcat() - Join Two Strings Together

The strcat() function is one of the common string functions in C; it appends one string to the end of another.

Syntax:

char *strcat(char *destination, const char *source);

Example:

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

int main() {
    char first[100] = "Hello, ";
    char second[] = "C programming!";

    strcat(first, second);  // Append 'second' to 'first'

    printf("Combined string: %s\n", first);
    return 0;
}

Output:

Combined string: Hello, C programming!

5. strstr() - Find a Substring in a String

strstr function in C looks for the first time a smaller string (called a substring) appears inside a bigger string. If it finds it, it returns a pointer to where it starts. If it doesn't find it, it returns NULL.

Syntax:

char *strstr(const char *mainString, const char *searchFor);

Example:

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

int main() {
    char sentence[] = "Learning C is fun";
    char *found = strstr(sentence, "C");

    if (found != NULL) {
        int position = found - sentence;
        printf("Substring found at position: %d\n", position);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}

Output:

Substring found at position: 9

6. strncpy() - Copy a Limited Number of Characters

Only a specific number of characters are copied through the source string to the target string using strncpy(). It is one of the string functions in C that comes in handy when you need to limit the length of the copy or avoid buffer overflows.

Syntax:

char *strncpy(char *destination, const char *source, size_t numCharacters);

Example:

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

int main() {
    char original[] = "Programming";
    char copy[20];

    // Copy only the first 5 characters
    strncpy(copy, original, 5);
    copy[5] = '\0';  // Manually add null terminator

    printf("Copied part: %s\n", copy);

    return 0;
}

Output:

Copied part: Progr

7. strncmp() - Compare First N Characters of Two Strings

The first n characters in both strings are compared using strncmp(). It helps check if part of the strings are the same. The function returns:

Syntax:

int strncmp(const char *str1, const char *str2, size_t n);

Example:

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

int main() {
    char word1[] = "apple";
    char word2[] = "apricot";

    int result = strncmp(word1, word2, 3);

    if (result == 0) {
        printf("First 3 characters are the same.\n");
    } else {
        printf("First 3 characters are different.\n");
    }

    return 0;
}

Output:

First 3 characters are the same.

8. memcpy() - Copy Memory (Can Be Used for Strings Too)

memcpy() copies a particular number of bytes from one memory location to another. It is utilized to copy data, such as arrays or strings, in a fast and efficient manner.

Syntax:

void *memcpy(void *destination, const void *source, size_t numberOfBytes);

Example:

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

int main() {
    char source[] = "Copy this text";
    char destination[50];  // Make sure it's big enough

    // Copy the string including the null terminator
    memcpy(destination, source, strlen(source) + 1);

    printf("Copied string: %s\n", destination);
    return 0;
}

Output:

Copied string: Copy this text

9. gets() and puts() - Input and Output for Strings

gets() was the function that took a user input line. puts() is used to output a string to the console, and a newline is added after the output.

Syntax:

fgets(str, size, stdin);

Example:

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);  // Safe input
    puts("You entered:");
    puts(name);  // Prints the string with a newline

    return 0;
}

Output:

Enter your name: Alice
You entered:
Alice

Additional and Less Common String Functions in C

Besides the standard string functions, C offers some extra and platform-specific functions that can be handy in certain situations. Even though not all of them are included in the official C standard, most of them can be found in widely-used compilers or libraries.

strlwr() - Convert String to Lowercase

Syntax:

char *strlwr(char *str);

Transforms all uppercase letters in the string to lowercase.

Note: Not part of the ISO C standard; available in some compilers (e.g., Turbo C, MSVC).

strupr() - Convert String to Uppercase

Syntax:

char *strupr(char *str);

Changes every lowercase letter in the given string to its uppercase equivalent.

Note: Like strlwr(), this is not standard but is supported by some compilers.

strset() - Set All Characters to a Specific Character

Syntax:

char *strset(char *str, int ch);

Sets every character in the string to the specified character ch.

Note: Not part of the ISO C standard; may not be available in all environments.

strdup() and strndup() - Duplicate Strings

Syntax:

char *strdup(const char *str);
char *strndup(const char *str, size_t n);

Note: These are POSIX functions and are available in many Unix-like systems.

strlcpy() and strlcat() - Safe Copy and Concatenation

Syntax:

size_t strlcpy(char *dest, const char *src, size_t size);
size_t strlcat(char *dest, const char *src, size_t size);

These functions copy or concatenate strings while ensuring the destination buffer is not overflowed and is null-terminated.

Note: Widely used on BSD systems and now available in glibc (Linux), but not part of the ISO C standard.

strpbrk() - Search for Any of a Set of Characters

Syntax:

char *strpbrk(const char *str, const char *accept);

Returns a pointer to the first occurrence in str of any character from accept, or NULL if none are found.

strerror() - Error Message String

Syntax:

char *strerror(int errnum);

Returns back a reference to a string that describes the error code entered as errnum.

Benefits of Using String Functions in C

1. Saves Time

C's built-in string functions help you get things done faster. Instead of writing the logic from scratch every time you want to copy, join, or compare strings, you can use functions like strcpy function in C, strcmp function in C, and strcat to do it in just one line.

2. Cleaner Code

Using these functions makes your code look much neater and easier to follow. It's clearer for you and others to read because the function names usually describe exactly what they do.

3. Better Performance

Most of the standard library functions are highly optimized, which means they perform faster than custom-written alternatives. You get good speed without extra effort.

Drawbacks of Using String Functions in C

1. Lack of Safety Checks

Many C string functions, such as strcpy function in C, don't check if the destination buffer is large enough. This can lead to buffer overflows, which are serious bugs and can even cause security issues.

2. Dependence on Null-Termination

C strings must end with a special character \0 to work properly. If you forget to include this null character, the string functions behave unpredictably.

3. Manual Memory Handling

Unlike modern languages or even C++'s std::string, C doesn't automatically manage memory for strings. You have to manually allocate and free memory, and resizing a string usually means creating a whole new buffer and copying everything over.

Conclusion

Working with strings is definitely a significant part of programming in C. Although C lacks built-in string types like some other modern languages, it offers efficient string functions in C via the <string.h> library. These functions make it easy to do things like get a string length through a strlen function in C or searching a substring using a strstr function in C.

That said, C requires you to be careful with memory and make sure strings are properly ended with a null character. Learning how to use these tools the right way will boost your C programming skills and help you understand how strings work at a low level.

Points to Remember

  1. strlen() scans memory until it finds \0. If your string is missing this terminator, the function will continue reading random bytes, leading to unpredictable output or crashes.

  2. strncpy() does NOT guarantee a null terminator when n characters are copied, meaning your "string" may not behave like a string at all unless you add \0 manually.

  3. Using strcat() without checking the remaining buffer size can overwrite adjacent variables, not just crash; it can silently corrupt your program's logic.

  4. Pointers returned by functions like strstr() or strchr() point inside the original string, not new memory; modifying them affects the original string.

  5. memcpy() is capable of copying ANY bytes, even the null terminator, therefore it is frequently the quickest method of copying raw text. However, if you use it on overlapping memory, the result will be undefined behavior (you should use memmove() in such cases).

Frequently Asked Questions

1. How to declare a string in C?

In C, a string is defined by an array of characters. For instance: char str[] = "Hello"; - the null character \0 is appended automatically.

2. What does the strlen() function do?

The total number of characters in a string, excluding the null terminator, is provided by the C strlen function.

3. How does strcmp() work when comparing strings?

When two strings are compared by strcmp(), it returns 0 if they are identical, a positive value if the first is lexicographically greater, and a negative value if the second is greater.

4. What is string concatenation in C?

It means joining two strings. You can use strcat(dest, src) to add src to the end of dest.

5. How to find a substring inside another string?

Use strstr function in C to search for a substring. It gives a pointer to the match or NULL if it's not found.

6. Why use string functions in C?

They make string handling functions in C easier, save time, and keep code clean, but you need to manage memory carefully.


Source: NxtWave - https://www.ccbp.in/blog/articles/string-functions-in-c