Finding Length of a String in C
To find the length of a string in C, we can use different methods such as the strlen()
function from the string.h
library, a manual character count using a loop, or pointer-based iteration.
In this tutorial, we will explore multiple ways to determine the length of a string with detailed explanations and examples.
Examples to Find String Length
1. Using strlen()
Function to Find Length of String
In this example, we use the strlen()
function from string.h
to determine the length of a string.
main.c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
printf("Length of the string: %d\n", length);
return 0;
}
Explanation:
- We declare a string
str
and initialize it with"Hello, World!"
. - The
strlen()
function calculates the length of the string, excluding the null character (\0
). - The result is stored in the integer variable
length
. - We print the length using
printf()
.
Output:
Length of the string: 13
2. Finding String Length Using a Loop
In this example, we manually count the characters in a string using a loop.
main.c
#include <stdio.h>
int main() {
char str[] = "Hello User";
int length = 0;
while (str[length] != '\0') {
length++;
}
printf("Length of the string: %d\n", length);
return 0;
}
Explanation:
- We declare a string
str
and initialize it with"C Programming"
. - The integer variable
length
is initialized to 0. - A
while
loop iterates through the string, increasinglength
until it encounters the null character (\0
). - Once the loop terminates,
length
holds the total number of characters in the string. - We print the length using
printf()
.
Output:
Length of the string: 10
3. Using Pointers to Find String Length
In this example, we use pointer arithmetic to determine the length of a string.
main.c
#include <stdio.h>
int main() {
char str[] = "Apple Banana";
char *ptr = str;
int length = 0;
while (*ptr != '\0') {
length++;
ptr++;
}
printf("Length of the string: %d\n", length);
return 0;
}
Explanation:
- We declare a string
str
and initialize it with"Pointer Example"
. - A pointer
ptr
is initialized to point to the first character of the string. - A
while
loop iterates through the string by incrementingptr
until it reaches the null character (\0
). - The
length
variable is incremented in each iteration to count the characters. - We print the length using
printf()
.
Output:
Length of the string: 12
Conclusion
In this tutorial, we explored different ways to find the length of a string in C:
- Using
strlen()
function: The easiest and most efficient way to get the string length. - Using a loop: A manual approach that counts characters until the null character.
- Using pointers: An optimized way to iterate through the string using pointer arithmetic.
Each method has its use case depending on whether you need standard library functions or low-level operations. The strlen()
function is recommended for most scenarios.