Problem Statement: Given a String, Calculate the Length of String in C.
Examples:
Example 1: Input: str = "Computer" Output: 8 Example 2: Input: str = "TUF" Output: 3
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Length of String: Number of characters in the string.
It’s simple as it sounds, we just need to traverse the string and simultaneously count the number of characters in the string.
The tricky part: To identify the end of the string or the last character of the string. In C, the last character in a string is the delimeter or ‘\0’. It is also pronounced as “Backslash zero”.
Approach:
Declare a variable count = 0, now we will traverse the whole string until we reach the end and will keep increasing the count variable by 1.
Code:
C program
#include<stdio.h>
int main()
{
char str[1000]= "TUF";
int i=0;
int count=0;
while(str[i]!='\0')
{
count++;
i++;
}
printf("The length of the string %d",count);
}
Output: The length of the string 3
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1).
Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article