Find size of string without using library functions in C++

In this tutorial, we will find the size of string without using library functions in C++. In many situations, you are compelled not to use library functions like strlen(). Well, in that case, there is a very simple method that can use to fulfill the task.

If you are here in search of solution the similar problem then you are at right place. I am providing you the solution of this problem that is based on a very basic concept of arrays.

This method will be useful in situations where you cannot afford to use library functions. Anyways I suggest you to use library functions over these methods because they reduce the efforts of the programmer and the program lines too.

Calculating the size of string without using library functions in C++

The data in an array is stored in the form of tables whose each box is numbered from 0 to the size of array. They are known as an index of array. The data when entered in array, get stored from position 0 to the size of the string entered and at the end of the string “\0” is automatically stored by the compiler. We are going to use this property of array to find the size of the string.

Code

I am using Code Blocks v 16.01 for this program. Anyways this will work without any issues on any other Idle.

#include <iostream>

using namespace std;

int main()
{
    char str[80];
    int length=0;               //This will store size of string
    cout<<"Enter the string: ";
    cin.getline(str,80);
    for(int i=0;str[i]!='\0';i++){  //It circulates the position of array
        length++;
    }
    cout<<"Length of the entered string is "<<length<<" bytes.";
    return 0;
}

 

Methodology




The code asks the user to enter the desired string then it will search for “\0” in the entire string from the starting of array. Also, it counts starting from the starting of string to the end until it finds “\0”. This count will give the length of the string.

We have now successfully calculated the size of the entered sting and that without using any library functions but a basic property of the array.

Example Output

Enter the string: programming
Length of the entered string is 11 bytes.

Hope you have understood the method and the code. Please drop your queries in the comment box below.

Also, read


Leave a Reply

Your email address will not be published. Required fields are marked *