Given a string str. The task is to find the length of the string.

Examples:
Input: str = "Geeks"
Output: Length of Str is : 5
Input: str = "GeeksforGeeks"
Output: Length of Str is : 13
In the below program, to find the length of the string str, first the string is taken as input from the user using scanf in
, and then the length of Str is calculated using
and using
method .
Below is the C program to find the length of the string.
Example 1: Using loop to calculate the length of string.
C
#include <stdio.h>
#include <string.h>
int main()
{
char Str[1000];
int i;
printf ( "Enter the String: " );
scanf ( "%s" , Str);
for (i = 0; Str[i] != '\0' ; ++i);
printf ( "Length of Str is %d" , i);
return 0;
}
|
OutputEnter the String: Length of Str is 0
Time Complexity: O(N)
Auxiliary Space: O(1)
Example 2: Using strlen() to find the length of the string.
C
#include <stdio.h>
#include <string.h>
int main()
{
char Str[1000];
int i;
printf ( "Enter the String: " );
scanf ( "%s" , Str);
printf ( "Length of Str is %ld" , strlen (Str));
return 0;
}
|
OutputEnter the String: Length of Str is 0
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 3: Using sizeof() to find the length of the string.
C
#include <stdio.h>
#include <string.h>
int main()
{
printf ( "Enter the String: " );
char ss[] = "geeks" ;
printf ( "%s\n" , ss);
printf ( "Length of Str is %ld" , sizeof (ss) - 1);
return 0;
}
|
OutputEnter the String: geeks
Length of Str is 5
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 4: Using Pointer Subtraction
C
#include <stdio.h>
int main()
{
char str[] = "Geeks" ;
char * ptr = str;
while (*ptr) {
ptr++;
}
printf ( "Address of start position of string : %x\n" ,
str);
printf ( "Address of end position of string : %x\n" , ptr);
int length = ptr - str;
printf ( "Length of the string: %d\n" , length);
return 0;
}
|
OutputAddress of start position of string : e996300
Address of end position of string : e996305
Length of the string: 5
Time Complexity: O(n)
Space Complexity: O(1)
Explanation
- In the main() function, a character array str[] is defined and initialized with the string “Greeks“.
- A pointer ptr is declared and initialized with the starting address of the str = e996300 array.
- The code enters a while loop that iterates until the value pointed to by ptr is not null. In C, the null character ‘\0‘ signifies the end of a string.
- Inside the loop, the ptr is incremented to point to the next character in the string.
- After the loop, the code calculates the length of the string by subtracting the starting address of str = e996300 from the final value of ptr = e996305. This pointer subtraction gives the number of elements (characters) between the two addresses
G | e | e | k | s | \0 |
---|
e996300 | e996301 | e996302 | e996303 | e996304 | e996305 |
Note: The address may be different in different execution of the above program.