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
If you've ever worked with strings in C, you’ve probably encountered the strlen() function. It’s one of the most commonly used tools in string handling, helping you figure out how long a string is (without counting the null-terminator).
But like most things in programming, it's easy to get caught up in the details and miss a few potential pitfalls. That’s why we’re diving into how strlen() function works, when and how to use it, and how to avoid the most common mistakes developers make. You can find all this in a top-tier software development course, but basics need to be cleared first.
By the end of this post, you'll have a solid understanding of how to use strlen() effectively and avoid those annoying bugs that can pop up if it’s not used properly.
So, you’ve probably come across the strlen() function if you’ve ever worked with strings in C. But what exactly is it?
Well, strlen() is a function in C that helps you figure out how long a string is. More specifically, it returns the number of characters in a string, excluding the null-terminator (`'\0'`). To understand it more efficiently, you should also undergo the functions concept, which includes user defined static function in C.
Must Explore: Introduction to C Tutorial
In C, strings are essentially arrays of characters, and the way we know where the string ends is by using that null-terminator (`'\0'`). The strlen() function in C walks through this array of characters and counts how many characters are there before it hits that null-terminator.
For example, if you have a string `"Hello"`, strlen() function will return `5`, because there are five characters in the string. Even though the string is technically stored as `{'H', 'e', 'l', 'l', 'o', '\0'}`, the `'\0'` isn't counted.
Here’s a quick peek at how you might use it:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length of string: %lu\n", strlen(str)); // Outputs 13
return 0;
}
In this example, the strlen() function will count the characters in `"Hello, World!"` and return `13`—just the actual characters, not the null-terminator.
Absolutely! Here’s a more concise yet detailed version of how to use strlen() in C:
Using strlen() in C is simple, but understanding how it works can help you avoid common mistakes. Let’s break it down:
To use strlen() function, include the `<string.h>` header file at the top of your program. This gives you access to strlen() and other string functions:
#include <string.h>
strlen() takes a single argument: a null-terminated string (an array of characters ending with `'\0'`). It counts the characters in the string up to, but not including, the null-terminator.
For example:
char str[] = "Hello"; // Stored as {'H', 'e', 'l', 'l', 'o', '\0'}
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
To get the length of a string, simply call strlen() and pass your string as the argument. It returns a `size_t` value, which represents the number of characters (excluding the null-terminator).
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, C World!";
size_t len = strlen(str); // Returns 17
printf("The length of the string is: %zu\n", len);
return 0;
}
Null-Terminator: strlen() function counts characters up to the null-terminator (`'\0'`). If your string isn't null-terminated, strlen() will not work correctly.
Edge Cases:
- An empty string (`""`) returns `0`.
- A string with only a null-terminator (`"\0"`) also returns `0`.
Non-null-Terminated Strings: If you pass a string without a null-terminator, strlen() can read past the allocated memory, causing undefined behavior or crashes.
char str[10] = {'H', 'e', 'l', 'l', 'o'}; // No null-terminator
printf("%zu\n", strlen(str)); // Undefined behavior!
Also Read: Static Function in C: Definition, Examples & Real-World Applications
strlen() might seem like a simple function, but it plays a crucial role in working with strings in C. Since C doesn’t have built-in string types like some other languages, strings are essentially arrays of characters, and knowing the length of a string is often necessary for many operations. Here's why strlen() function is so important:
When working with strings, you often need to know the string's length for various tasks, like:
Example:
for (size_t i = 0; i < strlen(str); i++) {
// Process each character in the string
}
Without strlen(), manually tracking the string's length would be error-prone and tedious.
In C, managing memory is a critical aspect of programming. Knowing the exact length of a string is essential when allocating memory dynamically or working with fixed-size buffers. For example, you need the length to avoid writing past the end of a buffer (which would cause undefined behavior or crashes).
To understand this and the further provided examples, you should first learn about the if-else statements in C.
Example:
char buffer[50];
size_t len = strlen(str);
if (len < sizeof(buffer)) {
strcpy(buffer, str); // Safe copy
}
Without knowing the length, you risk overwriting memory, leading to security vulnerabilities or bugs.
When reading input from the user or from files, you typically don’t know the size of the input string in advance. By using strlen() function, you can ensure that the input is properly handled, preventing buffer overflows and other memory errors.
Example:
char input[100];
fgets(input, sizeof(input), stdin);
printf("Input length: %zu\n", strlen(input)); // Safely process the input
Pursue DBA in Digital Leadership from Golden Gate University, San Francisco!
Many C string functions, such as `printf()`, `strtok()`, and `sprintf()`, expect strings to be null-terminated. Knowing the string length with strlen() ensures compatibility with these functions and helps avoid mishandling of the data.
In short, strlen() function is indispensable for handling strings in C because it allows for safe, efficient string manipulation, buffer management, and compatibility with other C string functions. Without it, working with strings would be cumbersome and error-prone.
The syntax of strlen() is simple and easy to use. Here’s a breakdown of how it works:
size_t strlen(const char *str);
str: This is the only parameter, and it’s the string you want to measure. It must be a valid null-terminated string (i.e., a sequence of characters that ends with the special character `'\0'`). The function counts all characters in the string up to, but not including, this null-terminator.
For example, if you pass the string `"Hello"` to strlen(), it will count the characters `{'H', 'e', 'l', 'l', 'o'}` and return `5`.
The function returns the number of characters in the string, excluding the null-terminator. The result is of type `size_t`, which can hold values large enough to represent the length of any string in memory.
#include <stdio.h>
#include <string.h>
int main() {
const char *message = "Hello, World!";
// Call strlen to get the length of the string
size_t length = strlen(message);
// Print the length of the string
printf("The length of the string is: %zu\n", length); // Outputs: 13
return 0;
}
In this example:
Check out the Executive Diploma in Data Science & AI with IIIT-B!
The strlen() function works by counting the number of characters in a string until it encounters the null-terminator (`'\0'`), which marks the end of the string. This process is straightforward but essential when dealing with strings in C. Additionally, its implementation also uses input and output functions, so, you should understand them too.
When you call strlen(), it starts from the first character of the string and keeps incrementing a counter until it hits the null-terminator. This means that for a string like `"Hello"`, strlen() function will:
The function then returns the count of characters it has encountered, excluding the null-terminator. So, for the string `"Hello"`, strlen() will return `5`, because there are 5 characters before the null-terminator.
Since strlen() function must go through the entire string one character at a time, its time complexity is ‘O(n)’, where ‘n’ is the number of characters in the string. It will keep counting until it finds the `'\0'`.
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
size_t len = strlen(str); // Returns 13
printf("Length: %zu\n", len); // Outputs: 13
return 0;
}
In this case, strlen() counts the 13 characters in `"Hello, World!"` and returns `13`.
Got it! Here's a breakdown of 3 basic, 2 intermediate, and 2 advanced use cases for strlen() with code examples, outputs, and step-by-step explanations.
Here, we’ve divided the code implementations into three categories. It’ll help you stronger the foundation and easily move to the advanced level of using strlen() function in C.
Purpose: This is the most basic use case—finding the length of a string using strlen() function. However, before you start with this program, it’s recommended to go through the manual procedure to determine the length of a string.
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, C!";
printf("Length of the string: %zu\n", strlen(str)); // Outputs: 9
return 0;
}
Explanation:
- strlen() counts the number of characters in the string, excluding the null-terminator.
- `"Hello, C!"` has 9 characters: `'H', 'e', 'l', 'l', 'o', ',', ' ', 'C', '!'`.
Output:
Length of the string: 9
Purpose: To check if a string is empty or not.
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "";
if (strlen(str) == 0) {
printf("The string is empty.\n");
} else {
printf("The string is not empty.\n");
}
return 0;
}
Explanation:
- strlen() returns `0` for an empty string, which allows us to detect it easily.
Output:
The string is empty.
Purpose: Validate whether user input is within an acceptable length.
#include <stdio.h>
#include <string.h>
int main() {
char input[50];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin); // Read user input
input[strcspn(input, "\n")] = '\0'; // Remove newline
// Validate length
if (strlen(input) < 10) {
printf("String is too short.\n");
} else {
printf("Input is valid.\n");
}
return 0;
}
Explanation:
- We use strlen() function to check if the length of the user input is less than 10 characters.
- The `fgets()` function is used to read the input, and `strcspn()` removes the newline character.
Example Input:
Hi there
Output:
String is too short.
Must Explore: Master User Defined Function in C: Practical Examples & Best Practices
Purpose: Safely concatenate two strings without causing buffer overflow.
#include <stdio.h>
#include <string.h>
int main() {
char str1[30] = "Hello, ";
const char *str2 = "World!";
// Ensure that the destination buffer has enough space
if (strlen(str1) + strlen(str2) < sizeof(str1)) {
strcat(str1, str2);
printf("Concatenated string: %s\n", str1); // Outputs: Hello, World!
} else {
printf("Buffer overflow risk! Can't concatenate.\n");
}
return 0;
}
Explanation:
- We check if the total length of both strings (source and destination) will fit in the destination buffer.
- This prevents potential buffer overflow issues.
Output:
Concatenated string: Hello, World!
Purpose: Iterate through each character of a string using its length.
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Iteration Example";
// Loop through the string using its length
for (size_t i = 0; i < strlen(str); i++) {
printf("Character %zu: %c\n", i, str[i]);
}
return 0;
}
Explanation:
- We use strlen() function to get the length of the string and iterate over each character.
- The loop prints each character's index and value.
Output:
Character 0: I
Character 1: t
Character 2: e
Character 3: r
Character 4: a
Character 5: t
Character 6: i
Character 7: o
Character 8: n
Character 9:
Character 10: E
Character 11: x
Character 12: a
Character 13: m
Character 14: p
Character 15: l
Character 16: e
Purpose: Safely copy one string to another using strlen() to check if the destination is large enough.
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Safe Copy!";
char dest[20];
// Ensure the destination buffer is large enough to hold the source string
if (strlen(source) < sizeof(dest)) {
strcpy(dest, source);
printf("Copied string: %s\n", dest); // Outputs: Safe Copy!
} else {
printf("Source string is too large to copy.\n");
}
return 0;
}
Explanation:
- strlen() function is used to compare the source string’s length to the destination buffer size.
- This prevents writing past the buffer’s limit and causing memory corruption.
Output:
Copied string: Safe Copy!
Purpose: Compare the lengths of two strings using strlen() and perform custom operations based on the result.
#include <stdio.h>
#include <string.h>
int main() {
const char *str1 = "Short String";
const char *str2 = "A Much Longer String";
if (strlen(str1) > strlen(str2)) {
printf("str1 is longer than str2.\n");
} else {
printf("str2 is longer than str1.\n"); // Outputs: str2 is longer than str1.
}
return 0;
}
Explanation:
- We use strlen() to compare the lengths of `str1` and `str2` and print the result.
- The comparison allows for decision-making based on string length.
Output:
str2 is longer than str1.
Also Read: String Input Output Functions in C
Here, we have provided all five comparisons of strlen() function in C to get rid of all the confusions and contrasting function complexities.
Function | Purpose | Behavior | Use Case | Limitations |
strlen() | Returns the length of a string (excluding null-terminator). | Iterates through the string counting characters until it reaches the null-terminator (\0). | Used when you need to know the length of a string. | Only works on null-terminated strings. |
strcpy() | Copies a string to another string. | Copies characters from the source string to the destination string until it encounters a null-terminator. | Used to copy one string to another (destination buffer must be large enough). | Does not check buffer size, can cause buffer overflow if not handled properly. |
Key Difference:
Function | Purpose | Behavior | Use Case | Limitations |
strlen() | Returns the length of a string. | Counts the number of characters up to the null-terminator. | Used to determine the length of a string. | Only works on null-terminated strings. |
strcmp() | Compares two strings lexicographically. | Compares each character of two strings until a difference is found or the null-terminator is reached. | Used to compare two strings for equality or order. | Does not return the length of the string, only compares them. |
Key Difference:
Must Explore: String Functions in C
Function | Purpose | Behavior | Use Case | Limitations |
strlen() | Returns the length of a string. | Counts the characters up to the null-terminator. | Used when you need to know the length of a string. | Works only on null-terminated strings. |
strcat() | Concatenates one string to another. | Appends the source string to the end of the destination string. The destination must be large enough to accommodate both strings. | Used to combine two strings into one. | Does not check for buffer overflow, which can cause issues if the destination buffer is too small. |
Key Difference:
Function | Purpose | Behavior | Use Case | Limitations |
strlen() | Returns the length of a string. | Counts the characters in the string until the null-terminator. | Used when you need to get the length of a string. | Only works on null-terminated strings. |
strncpy() | Copies up to n characters from one string to another. | Copies the first n characters from the source string to the destination string, padding with null bytes if the source string is shorter than n. | Used to copy a specific number of characters from one string to another, ensuring that it doesn't exceed a given length. | If the source string is longer than n, strncpy() does not null-terminate the destination string, potentially causing undefined behavior. |
Key Difference:
Also Read: If Statement in C
Method | Purpose | Behavior | Use Case | Limitations |
strlen() | Returns the length of a string. | Iterates through the string until the null-terminator is found, then returns the count of characters. | Used for getting the length of a string in a simple, efficient manner. | Requires a null-terminated string. |
Manual Length Calculation | Manually calculates the string length. | Loops through the string, checking each character until the null-terminator is reached. | Used when you don't have access to strlen() or if you're dealing with non-null-terminated strings. | Slower and more error-prone compared to strlen(). |
Key Difference:
You should also explore the data science course, if you’re looking for a great career in the IT field. The programming fundamentals will assuredly help in it.
Must Explore: Operator Precedence and Associativity in C
When using the strlen() function in C, there are several common pitfalls and errors that developers can run into. Here's a detailed breakdown of these issues, how to avoid them, and best practices to follow.
Pitfall:
strlen() relies on the null-terminator (`'\0'`) to determine where the string ends. If the string is not null-terminated, strlen() function may continue reading memory past the string’s end, resulting in unpredictable behavior, such as accessing invalid memory or causing segmentation faults.
How To Avoid:
Always ensure that the string is null-terminated. This is especially important when dealing with user input or strings manipulated manually.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[10] = {'H', 'e', 'l', 'l', 'o'}; // No null-terminator
printf("Length: %zu\n", strlen(str)); // Undefined behavior
return 0;
}
Solution:
Ensure that the string has a null-terminator:
#include <stdio.h>
#include <string.h>
int main() {
char str[10] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Null-terminator added
printf("Length: %zu\n", strlen(str)); // Correct output: 5
return 0;
}
Pitfall:
When passing a non-null-terminated array to strlen(), you can get undefined behavior because strlen() will not know where the string ends.
How To Avoid:
Always pass null-terminated strings to strlen() function. If working with a character array that is not null-terminated, either manually ensure a null-terminator or use alternative methods.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[5] = {'H', 'e', 'l', 'l', 'o'}; // No null-terminator
printf("Length: %zu\n", strlen(str)); // Undefined behavior
return 0;
}
Solution:
Ensure proper null-termination before passing to strlen():
#include <stdio.h>
#include <string.h>
int main() {
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Null-terminated string
printf("Length: %zu\n", strlen(str)); // Correct output: 5
return 0;
}
Pitfall:
strlen() function returns a value of type `size_t`, which is an unsigned data type. If you assign the result to an `int` or other signed type, you might encounter issues like truncation or unexpected results if the string length exceeds the limits of the data type.
How To Avoid:
Always assign the result of strlen() to a variable of type `size_t` (or any appropriate unsigned type).
Example:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
int length = strlen(str); // Incorrect: Potential for truncation if length is too large
printf("Length: %d\n", length);
return 0;
}
Solution:
Use `size_t` for storing the length:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
size_t length = strlen(str); // Correct: Using size_t
printf("Length: %zu\n", length); // Correct output: 13
return 0;
}
Pitfall:
Calling strlen() multiple times in a program (especially in loops) can be inefficient. strlen() performs a linear scan through the string each time it's called, which can result in poor performance if used repeatedly on the same string.
How To Avoid:
Store the result of strlen() in a variable if you need to reference the string length multiple times.
Example:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
for (size_t i = 0; i < strlen(str); i++) { // Inefficient: strlen() is called every iteration
printf("%c ", str[i]);
}
return 0;
}
Solution:
Store the result of strlen() in a variable:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
size_t len = strlen(str); // Store length in a variable
for (size_t i = 0; i < len; i++) {
printf("%c ", str[i]);
}
return 0;
}
Pitfall:
When reading input with `fgets()`, a newline character (`\n`) may be included at the end of the string. If you pass this string to strlen() without removing the newline, it will count it as part of the string length, which may not be what you intended.
How To Avoid:
After using `fgets()`, remove the newline character manually before passing the string to strlen().
Example:
#include <stdio.h>
#include <string.h>
int main() {
char input[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin); // Read input with newline
printf("Length (including newline): %zu\n", strlen(input)); // Counts newline
return 0;
}
Solution:
Remove the newline character after reading input:
#include <stdio.h>
#include <string.h>
int main() {
char input[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0'; // Remove newline character
printf("Length (without newline): %zu\n", strlen(input)); // Correct length
return 0;
}
Pitfall:
strlen() returns the number of characters in a string (excluding the null-terminator), while `sizeof()` returns the size of the variable or data type in bytes, which can be misleading when used with strings.
How To Avoid:
Understand the difference between strlen() and `sizeof()`. Use `sizeof()` for determining the size of a data type or array, and use strlen() to find the length of a string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("Using strlen(): %zu\n", strlen(str)); // 5
printf("Using sizeof(): %zu\n", sizeof(str)); // 6 (includes null-terminator)
return 0;
}
Solution:
Recognize that `sizeof(str)` returns the total size of the array, while `strlen(str)` gives the length excluding the null-terminator.
Pitfall:
You may accidentally pass a pointer to a string constant to strlen(), which is valid but can lead to misunderstandings. String constants are usually read-only, and modifying them can cause undefined behavior.
How To Avoid:
Always be cautious when passing string literals to strlen(), and ensure that you are not trying to modify them. Use `const` keyword to avoid accidental modification.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char *str = "Hello, World!"; // String constant
printf("Length: %zu\n", strlen(str)); // Fine, but be cautious if modifying
return 0;
}
Solution:
Mark the string as `const` if it's not meant to be modified:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!"; // Mark as const
printf("Length: %zu\n", strlen(str)); // Safe
return 0;
}
Interested in an MBA? If so, pursue an online MBA from Edgewood College, accredited by HLC and ACBSP!
In C programming, strlen() is a real lifesaver when you need to know the length of a string. Whether you're checking input sizes or performing string operations, it’s essential. However, like any tool, it can cause headaches if you don't use it right.
By keeping a few things in mind, like making sure your strings are null-terminated, using the right data types, and avoiding redundant calls to strlen() function, you can avoid common mistakes and make your code cleaner and safer. So, next time you reach for strlen(), you'll know exactly how to use it to its fullest potential without tripping over the usual issues.
If you pass a non-null-terminated string to strlen(), the function will continue reading memory beyond the intended end of the string until it encounters a null-terminator. This can result in undefined behavior, such as accessing invalid memory, which can cause segmentation faults or crashes.
No, strlen() does not count the null-terminator. It only counts the number of characters in the string up to, but not including, the null-terminator (`'\0'`). So, if a string is `"Hello"`, strlen() will return `5`.
strlen() is efficient for most cases, as it only scans the string once. However, if you call it multiple times for the same string, it may be inefficient because it will scan the string repeatedly. A good practice is to store the result of strlen() in a variable if you need to use the length multiple times.
No, strlen() is designed for single-byte, null-terminated strings (`char`). For wide-character strings, you should use `wcslen()`, which is specifically for wide-character (`wchar_t`) arrays.
When using `fgets()` to read input, the string might include a newline (`'\n'`) at the end. This newline will be counted by strlen(). To handle this, you can remove the newline by using `strcspn()` or manually replacing it with a null-terminator before passing the string to strlen().
For dynamically allocated strings, you can still use strlen() to find the length of the string as long as it is null-terminated. Just ensure that the string is properly null-terminated when calling strlen() to avoid undefined behavior.
strlen() returns the number of characters in a null-terminated string, excluding the null-terminator. `sizeof()`, on the other hand, returns the total size of the variable or type in bytes, which includes the null-terminator for static arrays. So, `sizeof()` will give the total memory size of the array, not just the string length.
strlen() can handle strings of any size, as long as they are within the limits of your system’s memory. The only real constraint is that the string must be null-terminated and the system must have enough memory to hold the string.
Yes, strlen() works on any null-terminated string. If the string is part of a larger structure or array, you can pass the correct part of the structure or array to strlen() as long as it is null-terminated.
If the string is empty (i.e., it contains only the null-terminator as the first character), strlen() will return `0`, indicating there are no characters in the string.
No, if a string contains a null character (`'\0'`) before the end of the string, strlen() will count only the characters up to the first null character. Any characters after that null character will not be counted by strlen().
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
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.