How do you find the length of a string in C?
In C programming, you can find the length of a string using the "strlen()" function. The "strlen()" function is part of the string.h header file in the standard C library. It calculates the length of a null-terminated string by counting the number of characters before the null-terminating character ('\0').
Find the length of a string in C |
Here's a explanation of how to find the length of a string in C with an example:
#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;
}
In this example, the string "Hello, World!" is stored in the character array "str". The "strlen()" function is then used to calculate the length of the string and store it in the integer variable "length". Finally, the length is printed using the printf() function.
The "strlen()" function iterates over the characters in the string until it encounters the null-terminating character ('\0'). It counts the number of characters before the null character and returns the length of the string as an integer.
It's important to note that the "strlen()" function does not count the null-terminating character itself as part of the string length. It only counts the characters that come before the null character.
Here's an example to demonstrate how "strlen()" works with a custom string:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
int length = strlen(str);
printf("Length of the string: %d\n", length);
return 0;
}
In this example, the string "Hello" is stored in the character array "str". The "strlen()" function counts the five characters ('H', 'e', 'l', 'l', 'o') and returns the length as 5.
The "strlen()" function is a convenient way to determine the length of a string in C. It is widely used in string manipulations, input validations, and various other programming tasks. Remember to include the "string.h" header file when using the "strlen()" function in your programs.