There are two approaches to finding the length of a string in C: using the strlen function, which is part of the string.h
library, and use a loop to iterate through the string and count the number of characters.
Find Length of String Using strlen Function
The C strlen
function can be used to find the length of a string, which is a string.h
library function. This function takes a string as an argument and returns its length (the number of characters in the string).
Here is an example of how to use strlen
to find the length of a string in C:
Example Program:
#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
printf("Enter a string: ");
scanf("%s", str);
int len = strlen(str);
printf("The length of the string is: %d\n", len);
}
Program Output:
Enter a string: w3schools
The length of the string is: 9
The above program reads a string from the user and then uses the strlen
function to find its length. The strlen
function returns the length of the string, which is stored in the variable len
. Finally, the program prints the length of the string using the printf
function.
Note that the strlen
function does not count the null character ('\0'
) at the end of the string, so the length of the string will be one less than the size of the array that holds the string.
Find Length of String Using Loop
To find the length of a string in C, you can use a loop to iterate through the string and count the number of characters. Here is an example of how you could do this:
Example Program:
#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
int i, length;
printf("Enter a string: ");
scanf("%s", str);
length = 0;
for (i = 0; str[i] != '\0'; i++)
{
length++;
}
printf("The length of the string is: %d\n", length);
}
Program Output:
Enter a string: www.w3schools.in
The length of the string is: 16
In the above program, the user is prompted to enter a string, which is then stored in the character array str
. The variable length
is initialized to 0
and is used to count the number of characters in the string.
The for
loop iterates through the string, starting at the first character (str[0]
) and ending when it reaches the null character ('\0'
), which marks the end of the string. The loop increments the value of length
on each iteration.
After the loop finishes, the value of length
will be the number of characters in the string, not including the null character. The length of the string is then printed to the screen using the printf
function.