Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C program to find the length of a string

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 Str     , and then the length of Str is calculated using loop     and using strlen()     method .
Below is the C program to find the length of the string.

Example 1: Using loop to calculate the length of string.

C




// C program to find the length of string
#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;
}


Output

Enter 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




// C program to find the length of 
// string using strlen function
#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;
}


Output

Enter 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




// C program to find the length of
// string using sizeof() function
#include <stdio.h>
#include <string.h>
  
int main()
{
  
    printf("Enter the String: ");
  
    char ss[] = "geeks";
  
    printf("%s\n", ss);
  
    // print size after removing null char.
    printf("Length of Str is %ld", sizeof(ss) - 1);
  
    return 0;
}
// This code is contributed by ksam24000


Output

Enter the String: geeks
Length of Str is 5

Time Complexity: O(1)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Last Updated : 19 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials