
Introduction
A string in C is a sequence of characters terminated by a null character '\0'
. Determining the length of a string is a fundamental operation in many programming tasks, as it is often necessary to know the string's length to manipulate it correctly, such as in loops, memory allocation, and comparison operations.
In this article, you will learn how to find the length of a string in C using different methods. Understand how to implement standard library functions and custom functions for this purpose through step-by-step examples.
Using the strlen() Function
Standard Library Approach
Include the
string.h
library which contains thestrlen()
function.Declare a string initialized with a character array.
Use
strlen()
to find the length of the string.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; }
This code initializes
str
with "Hello World" and usesstrlen()
to compute the length, which excludes the null terminator. The function returns the number of characters before the null character.
Implementing a Custom Function
Manual Loop Method
Define a function that takes a character array as an argument.
Initialize a counter to zero.
Use a while loop to increment the counter until the null character is encountered.
Return the counter as the length of the string.
c#include <stdio.h> int stringLength(const char str[]) { int length = 0; while (str[length] != '\0') { length++; } return length; } int main() { char str[] = "Example String"; int length = stringLength(str); printf("Length of the string: %d\n", length); return 0; }
This function,
stringLength
, manually iterates through the character arraystr
until it hits the null terminator, counting each character. It then returns the count, effectively giving the length of the string.
Conclusion
Determining the length of a string in C can be done effectively using the standard library's strlen()
function or by implementing a custom function that iterates through the string. Both methods are essential for handling strings in C, whether for manipulation, comparison, or other operations. By understanding how to measure string length, you ensure your string-handling code is robust and efficient.
No comments yet.