C Programming: Finding String Length with strlen() Function
Calculating String Length with strlen() Function in C
To design a function to calculate the length of a string using strlen in C, we can follow these steps:
Define the function prototype.
The function will take a pointer to the string as input and return an unsigned integer representing the length of the string.
unsigned int calculate_string_length(const char *string);
Implement the function body.
The function should iterate over the string characters until it encounters the null character ('\0')
. The number of characters iterated over will be the length of the string.
unsigned int calculate_string_length(const char *string) {
unsigned int length = 0;
while (*string != '\0') {
length++;
string++;
}
return length;
}
Test the function.
We can write a simple program to test the function as follows:
#include <stdio.h>
#include <string.h>
unsigned int calculate_string_length(const char *string);
int main() {
char string[] = "This is a test string.";
unsigned int length = calculate_string_length(string);
printf("The length of the string \"%s\" is %d.\n", string, length);
return 0;
}
unsigned int calculate_string_length(const char *string) {
unsigned int length = 0;
while (*string != '\0') {
length++;
string++;
}
return length;
}
Output:
The length of the string "This is a test string." is 20.
The calculate_string_length()
function can be used to calculate the length of any string in C. It is a simple and efficient function that is easy to use
Further Reading:
Implementation of strncat() in C
add source string at the end of destination string
comparing two string using strcmp and strncmp
Design a function to copy to copy string into destination string using strcpy and strncpy
how to implement implementation of strncpy in c
Design a function to calculate the length of the string using strlen
pre defined string based function
Design a function using my_strcpy and using my_strchr we need to select given char in given string
Enroll Now:
[ C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"
Contact Us:
- For any inquiries, please email us at [[email protected]].
- Follow us on insta [ electro4u_offical_ ] for updates and tips.
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!