How to find the length of a given string in C
In this tutorial, we are going to learn about two different ways to find the length of a string in C.
Using the strlen() function
The built-in strlen()
function helps us to find the length of a given string that is defined inside the string.h
header file.
The
strlen()
function takes thestring
as an argument and returns its length.
Example:
#include <string.h>
#include <stdio.h>
int main() {
char user[10] = "Gowtham";
int length = strlen(user);
printf("User length: %u", length);
}
Finding the length manually using for loop and while loop
We can also find the length of a string without using the str_len()
function, by manually looping through the each character in a string and store the count value in a variable.
For loop:
#include <stdio.h>
int main() {
char user[10] = "Gowtham";
int i = 0;
for (i; user[i] != '\0'; i++); printf("User length: %d", i);
return 0;
}
While loop:
#include <stdio.h>
int main() {
char user[10] = "Gowtham";
int i = 0;
while (user[i] != '\0'){ i++; } printf("User length: %d", i);
return 0;
}