C Exercises: Calculate the length of the string
10. String Length Using Pointer
Write a program in C to calculate the length of a string using a pointer.
Visual Presentation:
Sample Solution:
C Code:
#include <stdio.h>
// Function to calculate the length of the string
int calculateLength(char*); // Function prototype
int main() 
{
   char str1[25];
   int l;
   printf("\n\n Pointer : Calculate the length of the string :\n"); 
   printf("---------------------------------------------------\n");
   printf(" Input a string : ");
   fgets(str1, sizeof str1, stdin); // Input the string from the user
   l = calculateLength(str1); // Get the length of the input string
   printf(" The length of the given string %s is : %d ", str1, l-1); // Display the length of the string
   printf("\n\n");
}
// Function to calculate the length of the string
int calculateLength(char* ch) // Takes a pointer to the first character of the string
{
   int ctr = 0;
   while (*ch != '\0') // Loop until the null character '\0' is found
   {
      ctr++; // Increment the counter for each character encountered
      ch++; // Move to the next character in the string
   }
   return ctr; // Return the total count of characters (excluding the null character)
}
Sample Output:
Pointer : Calculate the length of the string : --------------------------------------------------- Input a string : w3resource The length of the given string w3resource is : 10
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to calculate the length of a string using pointer arithmetic without using strlen().
 - Write a C program to determine the length of a string recursively by advancing a pointer.
 - Write a C program to compute the length of a string and then compare it with a user-specified value.
 - Write a C program to find the string length and then reverse the string using pointer manipulation.
 
Go to:
PREV : Largest Element Using Dynamic Memory Allocation.
NEXT : Swap Elements Using Call by Reference.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
