+92 332 4229 857 99ProjectIdeas@Gmail.com

How to find the length of a string (C++)


Finding the length of a string
GetLength() takes a character array (string) as an input parameter and returns the length of the input string.
Summary of GetLength()
This function uses a count variable to store the length of the string and is initialized by 0. A for loop starts from the 0th index of the string and iterates till end. The end of the string is indicated by the NULL character ‘\0’ which is present at the end of every string. At each iteration of the for loop, the count variable is increamented by one and after the loop is terminated - the value of count variable is returned from the function.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

int GetLength( char * str )
{
       int length = 0;
      
       for ( int i = 0; str[i] != '\0'; i ++)
       {
              length = length + 1;
       }

       return length;
}

int main()
{
       char str[] = " Saad Bin Saulat ";
       cout << "Length of string : " << GetLength( str ) << endl;

       _getche();
       return 0;
}

Output
Length of string : 17

0 comments: