For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
When working on C programs, one of the most common tasks is handling strings. Whether it’s reading names, combining words, or comparing user inputs, string functions in C play a vital role in making these operations smooth and efficient. As you write and debug programs, you will often find yourself relying on these built-in functions to simplify your code and avoid errors.
Mastering string functions in C not only helps you write cleaner code but also saves time during development. Instead of manually manipulating character arrays, you can use ready-made functions to perform tasks like copying, concatenation, and comparison. In this article, we will explore these functions in depth, ensuring you understand their syntax, use cases, and behavior. You can also explore our in-depth Software engineering courses.
String functions in C are built-in library functions used to perform operations on strings, such as finding their length, copying, comparing, or concatenating them. These functions are declared in the <string.h> header file, which must be included at the top of your program.
Boost your skills by enrolling in these top-rated programs:
The general syntax is:
#include <string.h>
return_type function_name(arguments);
For example:
#include <string.h>
int len = strlen(str);
Using string functions in C saves time, reduces errors, and avoids the need to manually loop through character arrays. They help make programs more readable and maintainable.
In C, a string is an array of characters ending with a null character '\0'. You can declare and initialize strings in several ways.
Example: Declaring and Initializing a String
#include <stdio.h>
int main() {
char name[20] = "Ram";
printf("%s\n", name);
return 0;
}
Output:
Ram
Explanation: We declare a character array name with a size of 20 and initialize it with "Ram". The %s format specifier prints the string.
String functions in C can be broadly categorized as:
1. strlen() {Find Length}
c
CopyEdit
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Shyam";
printf("Length: %lu\n", strlen(str));
return 0;
}
Output:
Length: 5
Explanation: strlen() returns the number of characters before '\0'. "Shyam" has 5 letters.
2. strcpy() {Copy String}
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Aniket";
char dest[20];
strcpy(dest, src);
printf("Copied String: %s\n", dest);
return 0;
}
Output:
Copied String: Aniket
Explanation: strcpy() copies src into dest including the null terminator.
3. strcat() {Concatenate Strings}
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Prasun ";
char str2[] = "Ankita";
strcat(str1, str2);
printf("Concatenated String: %s\n", str1);
return 0;
}
Output:
Concatenated String: Prasun Ankita
Explanation: strcat() appends str2 at the end of str1.
4. strcmp() {Compare Strings}
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Pooja";
char str2[] = "Pooja";
int result = strcmp(str1, str2);
printf("Comparison Result: %d\n", result);
return 0;
}
Output:
Comparison Result: 0
Explanation: strcmp() returns 0 if both strings are equal.
Must Explore: String Pointer in C
To input and output strings, you can use scanf(), printf(), gets() (unsafe), or fgets().
#include <stdio.h>
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
Output:
Enter your name: Ram
Hello, Ram!
Explanation: scanf("%s", name) reads a word. printf() displays it with a greeting.
Sometimes, you may need to manually handle strings, especially in academic tasks.
Example of Calculating Length Without strlen()
#include <stdio.h>
int main() {
char str[] = "Aniket";
int i = 0;
while (str[i] != '\0') {
i++;
}
printf("Length: %d\n", i);
return 0;
}
Output:
Length: 6
Explanation: We loop through the string until we hit '\0', incrementing i on each iteration.
Do check out: Comprehensive Guide to String Comparison in C
Here are the most frequently used functions:
strchr() {Find Character}
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "RamShyam";
char *ptr = strchr(str, 'S');
if (ptr) {
printf("Found at position: %ld\n", ptr - str);
} else {
printf("Not found\n");
}
return 0;
}
Output:
Found at position: 3
Explanation: strchr() returns a pointer to the first occurrence of 'S'.
strstr() {Find Substring}
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello Aniket";
char *ptr = strstr(str, "Aniket");
if (ptr) {
printf("Substring starts at: %ld\n", ptr - str);
} else {
printf("Substring not found\n");
}
return 0;
}
Output:
Substring starts at: 6
Explanation: strstr() finds the position where the substring "Aniket" starts.
Here’s a complete program using multiple string functions together.
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello ";
char str2[] = "Pooja";
char str3[50];
strcpy(str3, str1);
strcat(str3, str2);
printf("Combined String: %s\n", str3);
printf("Length: %lu\n", strlen(str3));
if (strcmp(str1, str2) == 0) {
printf("Both strings are equal\n");
} else {
printf("Strings are different\n");
}
return 0;
}
Output:
Combined String: Hello Pooja
Length: 11
Strings are different
Explanation: We copy, concatenate, check length, and compare the strings. This shows multiple string functions in C working together.
String functions in C simplify string handling and make programs more efficient, readable, and robust. Instead of writing long loops to manage character arrays, these functions let you perform tasks like copying, concatenating, comparing, and searching with just a single line of code. This not only saves development time but also reduces the chances of introducing bugs, especially when working on large or complex programs.
For beginners, using string functions in C is an excellent way to avoid common mistakes such as buffer overflows, wrong loop boundaries, or missing null characters. These functions are well-tested and optimized, so they help you write cleaner and more maintainable code. As you practice these functions, you will also gain a deeper understanding of how strings work at the memory level in C, which is essential for mastering the language.
Moreover, learning string functions in C builds a solid foundation for advancing to more complex topics, such as dynamic memory allocation, file handling, and data structures like linked lists. With a good grasp of these functions, you’ll write more professional, efficient, and secure programs. Keep experimenting with them in small projects or assignments, and you will soon become confident in your ability to handle any string operation in C.
String functions in C help perform operations like copying, comparing, concatenating, and finding the length of strings. They make string handling easier and reduce the risk of common errors in manual implementations.
The strcpy() function copies the contents of one string into another. It ensures the destination string contains the same characters, including the null character, as the source string, replacing its previous contents.
strncpy() copies a specific number of characters and stops after reaching the limit, while strcpy() copies until the null character. strncpy() helps prevent buffer overflows and is generally safer in real-world applications.
You can concatenate two strings in C using the strcat() function. It appends the second string to the end of the first string, ensuring the combined string ends with the null character.
The strcmp() function compares two strings character by character. It returns zero if the strings are equal, a positive value if the first is greater, and a negative value if the second is greater.
Use the strlen() function to measure the length of a string in C. It counts the number of characters before the null character, excluding the null terminator itself, and returns this length as an integer.
The null character (\0) marks the end of a string in C. All string functions rely on this character to determine where the string stops, ensuring operations like copying and comparing work correctly.
The strchr() function searches for the first occurrence of a character in a string. It returns a pointer to that character if found or NULL if the character does not exist within the string.
strstr() searches for a substring inside a string, while strchr() looks for a single character. Both return pointers if found, helping you locate positions within the string efficiently.
You can copy part of a string using the strncpy() function. It allows you to specify the maximum number of characters to copy, making it useful for working with substrings or fixed-size buffers.
To avoid buffer overflow, use functions like strncpy() and always ensure the destination array has enough space for the copied or concatenated string, including the null character at the end.
Yes, most string functions in C, like strcmp() and strstr(), are case-sensitive. This means uppercase and lowercase letters are treated as different, so comparisons and searches must account for this.
Use the strcasecmp() or _stricmp() function, depending on your compiler. These functions compare strings without considering letter case, making them useful when case should not affect the comparison result.
Yes, you can create custom string functions in C to handle specific needs. By using loops and conditions, you can build functions like reverse, replace, or count, which are not provided in the standard library.
Practicing string functions in C helps beginners understand memory handling, pointers, and array manipulation. It builds confidence, improves problem-solving skills, and prepares them for more advanced programming concepts and challenges.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.