C Program to Find the Length of the String

The length of a string can be determined using the built-in library function strlen() in the “string.h” header file.

Examples:

String: “Hello”
Length of the string is: 5

String: “Sanfoundry”
Length of the string is: 10

Problem Description

Write a C Program to find the length of a String.

Problem Solution

1. Take a string as input and store it in the array.
2. Using for loop count the number of characters in the array and store the result in a variable.
3. Print the variable as output.

advertisement
advertisement

There are several ways to find the length of the string in C language. Let’s take a detailed look at all the approaches to find the length of a string in C.

Method 1: Length of the String in C without using Built-in Function

In this approach we use the iterative statement to find the length of string using for loop. We start from the first character and traverse the whole string until we encounter the backspace character (‘\0‘), which marks the end of the string.

Example:

String: “Hello”

The actual representation of this string is: [ ‘H’ ,’e’ , ‘l’ , ‘l’ , ‘o’ , ‘\0’ ]

We traverse until a backspace character is encountered, So Length of the string is 5.

Program/Source Code

Here is source code of the C program to find the length of a string without using the built-in function.The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1.  
  2. /*
  3.  * C program to find the length of a string without using the
  4.  * built-in function
  5.  */
  6.  
  7. #include <stdio.h>
  8.  
  9. void main()
  10. {
  11.     char string[50];
  12.     int i, length = 0;
  13.  
  14.     // input the string
  15.     printf("Enter the string: \n");
  16.     gets(string);
  17.     /*  keep going through each character of the string till its end */
  18.     for (i = 0; string[i] != '\0'; i++)
  19.     {
  20.         length++;
  21.     }
  22.     printf("The length of a string is the number of characters in it \n");
  23.     printf("So, the length of %s = %d\n", string, length);
  24. }
Program Explanation

1. Take a string as input and store it in the array string[].
2. Using for loop count the number of characters in the array string[]. Use the variable length to keep the count of the characters in the array.
3. Do step-2 till the end of input string.
4. Print the variable length as output.

advertisement

Time Complexity: O(n)
In the for loop we are iterating over the string until we encounter the backspace character, so time complexity is O(n), where n is length of string.

Space Complexity: O(n)
Space is required to store a sting, so the space complexity of string length program is O(n).

Runtime Test Cases

In this case, we enter the string “Hello” as input to find the length of the string.

Enter a string: Hello
The length of a string is the number of characters in it
So, the length of Hello = 5

Method 2: Length of the String in C using While Loop
advertisement

In this approach, we use the iterative statement to find the length of string using while loop. We start from the first character and traverse the whole string until we encounter the backspace character (‘\0‘), which marks the end of the string.

Example:

String: “Sanfoundry”

The actual representation of this string is: [ ‘S’ ,’a’ , ‘n’ , ‘f’ , ‘o’ , ‘u’ , ‘n’ , ‘d’ , ‘r’ , ‘y’ ,‘\0’ ]

We traverse until a backspace character is encountered, So Length of the string is 10.

Program/Source Code

Here is source code of the C program to find the length of a string without using the built-in function.The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to find the length of a string using the while loop
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. int main ()
  8. {
  9.     int length=0;
  10.     char string[30];
  11.  
  12.     // input the string
  13.     printf ("Enter the string: \n");
  14.     gets (string);
  15.  
  16.     //Traversing until a backspace character is encountered which mark end of string
  17.     while (string[length] != '\0')
  18.         length ++;
  19.     printf("Length of string is: %d",length);
  20.  
  21.     return 0;
  22. }
Program Explanation

1. Take a string as input and store it in the array string[].
2. Initialize length variables as 0.
3. Traverse the string until the backspace character is encountered and in each step increment the length variable.
4. Print the Length of the string.

Time Complexity: O(n)
In the for loop we are iterating over the string until we encounter the backspace character, so time complexity is O(n), where n is length of string.

Space Complexity: O(n)
Space is required to store a sting, so the space complexity is O(n).

Runtime Test Cases

In this case, we enter the string “Sanfoundry” as input to find the length of the string.

Enter the string: Sanfoundry
Length of string is: 10

Method 3: Length of the String in C using Strlen Function

The best way to find the length of a string is using the built-in library function i.e. strlen()

strlen function:

Function Prototype: int strlen(const char *s1)
Return Value: returns the length of string

Example:

Input: String = “Sanfoundry Programs”

Output: Length of string is: 19

Program/Source Code

Here is source code of the C program to find the length of a string using strlen function. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to find the length of a string using strlen function
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <string.h>
  7. int main ()
  8. {
  9.     char string[30];
  10.  
  11.     // input the string
  12.     printf ("Enter the string\n");
  13.     gets (string);
  14.  
  15.     // Storing value of strlen function
  16.     int length = strlen(string);
  17.     printf("Length of string is: %d",length);
  18.     return 0;
  19. }
Program Explanation

1. Take a string as input and store it in the array string.
2. Call the strlen() function and store its value in the length variable.
3. Print the Length of the string.

Time Complexity: O(n)
Time complexity of the standard strlen function is O(n), where n is length of string.

Space Complexity: O(n)
Space is required to store a sting, so the space complexity is O(n).

Runtime Test Cases

In this case, we enter the string “Sanfoundry Programs” as input to find the length of the string.

Enter the string: Sanfoundry Programs
Length of string is: 19

Method 4: Length of the String in C using Recursion

In this approach, we will find the length of the string using recursion.

Example:

String: “Hello”

Len(“Hello”) = return  1 + Len(“ello”)---------------------------------------------  5
                           return 1 + Len(“llo”)-----------------------------------  4
                                      return  1 + Len(“lo”)------------------------- 3
                                                  return 1 + Len(“o”)--------------- 2
                                                             return 1 -------------- 1
Program/Source Code

Here is source code of the C program to find the length of a string using recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to find the length of a string using recursion
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <string.h>
  7.  
  8. int length(char str[],int i)
  9. {
  10.     //Base case
  11.     if(str[i]=='\0')
  12.     return 0;
  13.  
  14.     //Recursive calls
  15.     return 1 + length(str,i+1);
  16. }
  17. int main ()
  18. {
  19.     char string[30];
  20.  
  21.     // input the string
  22.     printf ("Enter the string\n");
  23.     gets (string);
  24.  
  25.     // Calling length function
  26.     int len = length(string,0);
  27.     printf("Length of string is: %d",len);
  28.     return 0;
  29. }
Program Explanation

1. Take a string as input and store it in the array string.
2. Declare function to find length which recursively calls itself and return (1 +Length of rest string) with a base case to stop when a backspace character is encountered.
3. Print value returned by function as the length of string.

Time Complexity: O(n)
As there are n function calls, the time complexity is O(n), where n is the length of the string.

Space Complexity: O(n)
Space is required to store a sting, so the space complexity is O(n).

Runtime Test Cases

In this case, we enter the string “Hello” as input to find the length of the string.

Enter the string: Hello
Length of string is: 5

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.