Welcome to our comprehensive guide on the C strlen() function! In this tutorial, we'll delve deep into understanding this essential function, explore its practical usage, and provide you with working examples. Let's get started! 🎯
The strlen() function in C is used to determine the length of a string. It returns the number of characters (excluding the null character \0) in the given string. 📝
The syntax of the strlen() function is as follows:
int strlen(const char *str);The str parameter is a character pointer that points to the beginning of the string.
The strlen() function works by iterating through the string from the starting point (address stored in the pointer) until it encounters the null character (\0). By keeping a counter, it calculates the length of the string. 💡
Let's illustrate the strlen() function with a simple example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
printf("The length of the string is: %d\n", length);
return 0;
}In this example, we have a string "Hello, World!", which is stored in an array str. We call the strlen() function to calculate the length of the string, and then print the result.
Upon executing the code, you should see the output:
The length of the string is: 13
In some cases, you might not know the exact length of the string at the time of writing the code. In such situations, you can use dynamic memory allocation to store the string and calculate its length using strlen().
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int len = 0;
char *str = (char*)malloc(len * sizeof(char)); // Initialize with zero length
printf("Enter a string: ");
char ch;
while ((ch = getchar()) != '\n') {
str = (char*)realloc(str, ++len * sizeof(char));
str[len - 1] = ch;
}
int str_len = strlen(str);
printf("The length of the entered string is: %d\n", str_len);
free(str); // Don't forget to free the memory!
return 0;
}In this example, we dynamically allocate memory for the string and take user input. After entering the string, we calculate its length using strlen(). Finally, we free the allocated memory.
What does the `strlen()` function in C return?
We hope you found this tutorial helpful and engaging! In the next lesson, we'll explore more C functions that will help you on your coding journey. 😊 Happy learning! 🎓