Fill your College Details

Summarise With AI
Back

Complete Guide on String Functions in C

12 Dec 2025
5 min read

What This Blog Covers

  • Getβ€‹β€β€‹β€Œβ€β€‹β€β€Œβ€‹β€β€‹β€Œβ€β€‹β€β€Œs insight into the internal working of strings in C, that is not as objects but as character arrays ending with \0, and comprehend why this low-level implementation is significant for memory, performance, and debugging.
  • Master the skill to properly declare, initialize, and access strings through the use of arrays and pointers, with understandable examples that are free from the types of mistakes typical of β€‹β€β€‹β€Œβ€β€‹β€β€Œβ€‹β€β€‹β€Œβ€β€‹β€β€Œstudents.
  • Master 12 essential String Functions in C, like strlen, strcpy, strcmp, strcat, strncpy, strstr, memcpy, and more, including syntax, parameters, and output.
  • Explore advanced & non-standard functions (strlwr, strupr, strdup, strlcpy, etc.) that real-world systems and compilers use for safer string handling.
  • Getβ€‹β€‹β€Œβ€‹β€Œβ€‹β€‹β€Œβ€‹β€Œ real-world knowledge, safety guidelines, and efficiency suggestions so that you can keep away from buffer overflows, missing null terminators, and segmentation faults, which are, by far, the most common mistakes in student assignments and interviews.

Introduction

Handlingβ€‹β€β€‹β€Œβ€β€‹β€β€Œβ€‹β€β€‹β€Œβ€β€‹β€β€Œ strings in C can be quite confusing at times as C do 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. Some common things you can do with string functions include:

  • Finding how long a string is using strlen function in C
  • Copying one string to another with strcpy function in C.
  • Checking if two strings are the same using strcmp function in C.
  • Joining two strings together with strcat().
  • Looking for one string inside another using the strstr function in C.

🎯 Calculate your GPA instantly β€” No formulas needed!!

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

Syntax:

size_t strlen(const char *str);

Parameters:

  • str: Pointer to the null-terminated string whose length is to be determined.

Returns:

  • The number of characters in the string, not including the null terminator.

strcpy

Syntax:

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

Parameters:

  • destination: Pointer to the array to which the content will be transferred.
  • source: Pointer to the null-terminated string to copy.

Returns:

  • Returns destination.

strncpy

Syntax:

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

Parameters:

  • destination: Pointer to the destination array.
  • source: Pointer to the source string.
  • n: Maximum number of characters to copy.

Returns:

  • Returns destination.

strcat

Syntax:

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

Parameters:

  • destination: Pointer to the destination null-terminated string.
  • source: Pointer to the source string to append.

Returns:

  • Returns destination.

strncat

Syntax:

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

Parameters:

  • destination: Pointer to the destination string.
  • source: Pointer to the source string.
  • n: Maximum number of characters to append.

Returns:

  • Returns destination.

strcmp

Syntax:

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

Parameters:

  • str1, str2: Pointers to the two null-terminated strings to compare.

Returns:

  • 0 if strings are equal
  • Positive value if str1 > str2
  • Negative value if str1 < str2

strncmp

Syntax:

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

Parameters:

  • str1, str2: Strings to compare.
  • n: Maximum number of characters to compare.

Returns:

  • 0 if the first n characters are equal
  • Positive or negative value as above

strchr

Syntax:

char strchr(const char str, int ch);

Parameters:

  • str: String to search.
  • ch: Character to find (interpreted as char).

Returns:

  • Pointer to the very first occurrence of ch in str, or NULL if not found.

strrchr

Syntax:

char strrchr(const char str, int ch);

Parameters:

  • str: String to search.
  • ch: Character to find.

Returns:

  • A pointer to the most recent instance of the character ch, or NULL in the event that it cannot be located.

strstr

Syntax:

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

Parameters:

  • haystack: String to search in.
  • needle: Substring to search for.

Returns:

  • Pointer to the very first occurrence of needle in haystack, or NULL if not found.

sprintf

Syntax:

int sprintf(char str, const char format, …);

Parameters:

  • str: Buffer where the formatted string will be stored.
  • format: Format string (similar to printf).Β 
  • Additional arguments as required by the format.

Returns:

  • Number of characters written (not including the null terminator).

strcspn

Syntax:

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

Parameters:

  • str1: String to be scanned.
  • str2: String containing characters to match.

Returns:

  • Length of the segment in str1 not containing any characters from str2.

strset (non-standard, may not be available on all systems)

Syntax:

char strset(char str, int ch);

Parameters:

  • str: String to modify.
  • ch: Character to set.

Returns:

  • Returns str.

strtod, strtof, strtold

Syntax:

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

Parameters:

  • str: String to convert.
  • endptr: Pointer to a pointer to a character; set to the character after the last parsed character.

Returns:

  • The converted floating-point value.

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.

  • Returns 0 if both strings are the same
  • Returns a positive number if the first string is greater
  • Returns a negative number if the second string is greater

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.

  • destination: The string you want to add to.
  • source: The string you want to add from.

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:

  • 0 if the first n characters are the same
  • A negative number if the first string is smaller
  • A positive number if the first string is bigger

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);
  • strdup() allocates memory and copies the given string, returning a pointer to the duplicate.
  • strndup() duplicates up to n characters. 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.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert