Published: 12 Dec 2025 | Reading Time: 5 min read
This comprehensive guide provides detailed coverage of string functions in C programming:
Internal Working of Strings: Understand how strings work in C as character arrays ending with \0, and why this low-level implementation is significant for memory, performance, and debugging.
String Declaration and Initialization: Master the skill to properly declare, initialize, and access strings through the use of arrays and pointers, with understandable examples that are free from common student mistakes.
Essential String Functions: Master 12 essential string functions in C, including strlen, strcpy, strcmp, strcat, strncpy, strstr, memcpy, and more, with complete syntax, parameters, and output details.
Advanced Functions: Explore advanced and non-standard functions (strlwr, strupr, strdup, strlcpy, etc.) that real-world systems and compilers use for safer string handling.
Safety and Best Practices: Get real-world knowledge, safety guidelines, and efficiency suggestions to avoid buffer overflows, missing null terminators, and segmentation faults—the most common mistakes in student assignments and interviews.
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.
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:
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.
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.
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.
char greeting[] = "Hello";
In this case, the compiler determines the size automatically based on the string literal, including the null character.
C supports several forms of string initialization, depending on whether the programmer uses string literals, character arrays, or pointers.
char name[] = "John";
The compiler stores the characters followed by '\0'.
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.
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.
Strings can be accessed either through array indexing or pointer arithmetic.
char language[] = "C Language";
printf("%c", language[0]); // Output: C
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.
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.
Syntax:
size_t strlen(const char *str);
Parameters:
str: Pointer to the null-terminated string whose length is to be determined.Returns:
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:
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:
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:
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:
Syntax:
int strcmp(const char *str1, const char *str2);
Parameters:
str1, str2: Pointers to the two null-terminated strings to compare.Returns:
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:
Syntax:
char *strchr(const char *str, int ch);
Parameters:
str: String to search.ch: Character to find (interpreted as char).Returns:
Syntax:
char *strrchr(const char *str, int ch);
Parameters:
str: String to search.ch: Character to find.Returns:
Syntax:
char *strstr(const char *haystack, const char *needle);
Parameters:
haystack: String to search in.needle: Substring to search for.Returns:
Syntax:
int sprintf(char *str, const char *format, ...);
Parameters:
str: Buffer where the formatted string will be stored.format: Format string (similar to printf).Returns:
Syntax:
size_t strcspn(const char *str1, const char *str2);
Parameters:
str1: String to be scanned.str2: String containing characters to match.Returns:
Syntax:
char *strset(char *str, int ch);
Parameters:
str: String to modify.ch: Character to set.Returns:
Note: Non-standard function, may not be available on all systems.
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:
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.
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.
strlen function in C calculates how many characters are in a string, not counting the null terminator (\0) at the end.
size_t strlen(const char *str);
#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;
}
The string length is: 13
strcpy function in C copies the content from one string (source) to another string (destination).
char *strcpy(char *destination, const char *source);
#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;
}
Copied string: Learning C
strcmp function in C is used to compare two strings character by character. It checks the strings in dictionary (lexicographic) order.
int strcmp(const char *str1, const char *str2);
#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;
}
"apple" comes before "banana".
The strcat() function is one of the common string functions in C; it appends one string to the end of another.
char *strcat(char *destination, const char *source);
#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;
}
Combined string: Hello, C programming!
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.
char *strstr(const char *mainString, const char *searchFor);
#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;
}
Substring found at position: 9
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.
char *strncpy(char *destination, const char *source, size_t numCharacters);
#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;
}
Copied part: Progr
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:
int strncmp(const char *str1, const char *str2, size_t n);
#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;
}
First 3 characters are the same.
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.
void *memcpy(void *destination, const void *source, size_t numberOfBytes);
#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;
}
Copied string: Copy this text
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.
fgets(str, size, stdin);
#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;
}
Enter your name: Alice
You entered:
Alice
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.
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).
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.
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.
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.
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.
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.
Syntax:
char *strerror(int errnum);
Returns back a reference to a string that describes the error code entered as errnum.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Using strcat() without checking the remaining buffer size can overwrite adjacent variables, not just crash; it can silently corrupt your program's logic.
Pointers returned by functions like strstr() or strchr() point inside the original string, not new memory; modifying them affects the original string.
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).
In C, a string is defined by an array of characters. For instance: char str[] = "Hello"; - the null character \0 is appended automatically.
The total number of characters in a string, excluding the null terminator, is provided by the C strlen function.
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.
It means joining two strings. You can use strcat(dest, src) to add src to the end of dest.
Use strstr function in C to search for a substring. It gives a pointer to the match or NULL if it's not found.
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