Press "Enter" to skip to content

C++ : Length of a String with and without Strlen Function

Length of a string in C++ is a common question in C++ exam or interview. You can find the length of a given using inbuilt system function or using manual codes.

Using strlen function

Strlen is a system function used to find length of any string without further codes. So it’s easy to implement. Here you need to import a header file ‘string.h’.

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char text[20];
    int length;
    cout << "Type a string :" << endl;
    cin>>text;
    cout<<text;
    length= strlen(text);
    cout<<"Length of given string is "<<length;
    return 0;
}

Length of a string without strlen function

As we shown the above code, which is easy. So majority of exam prefer manual code to find the length of a string without strlen function.

#include <iostream>
using namespace std;

int main()
{
    char text[20];
    int length= 0;
    cout << "Type a string :";
    cin>>text;

    for(int i = 0; text[i] != '\0' ; i++)
    {
         length= length+ 1;
    }
    cout<<"Length of given string is "<<length;
    return 0;
}

Output:

C++  Length of a String with and without Strlen Function

Logic: In above code, string is stored on an array. In array, while storing string, there should be an extra element ‘\0’ at the end of the string.

So inside the for loop, we limit the loop until this element (\0). A variable ‘length’ increment on each iteration and if array reaches the element ‘\0’, that will be end and variable ‘length’ will be the length of the given string.

Be First to Comment

Leave a Reply