C++

How to Find Length of String in C++

In C++, the string is an object of the “std::string” class that is known as an array of characters or an unordered series of characters. In simple words, strings are the collection of characters enclosed among double quotes and represented as an array of characters followed by a null character at the end. With string, we users can perform multiple operations, such as comparison, concatenation, conversion, and many more.

In this guide, we will cover:

How to Initialize String Variables in C++?
How to Find Length of String in C++?
How to Find String Length Using Built-in Functions in C++?

How to Find Length of String With User-defined Function in C++?
Use C Library Function in C++ to Find String Length
How to Find String Length Using Loops in C++?

How to Find Length of String Using Pointers in C++?
How to Find Length of String Using Recursive Method in C++?

Bottom Line

How to Initialize String Variables in C++?

To initialize a string variable, users need to specify the string data type then the name of the variable will be added. For instance, if users want to store the alpha-numeric variable “demo = “3 apples”;”. Initially, they will use the string data type, then the variable name and the string variable will be “string demo = “3 apples”;”.

How to Find Length of String in C++?

There are multiple methods available in C++ to get the length of the string, such as:

  • Using Built-in Functions
  • User-defined Function
  • Using C Library Function
  • Using Loops
  • Using Pointers
  • Using Recursive Method

Now, move forward and check out the working of these methods one by one!

How to Find String Length Using Built-in Functions in C++?

C++ provides some built-in functions that are utilized for retrieving the length of the string, which are listed below:

  • size() Function
  • length() Function

Find String Length Using Using “size()” Function in C++

The “size()” is the most popular built-in function of the C++ that can be used for calculating the string length. For better understanding, let’s have a look at the provided example code:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
 string my_str = "Welcome to LinuxHint World!!";
 cout << "The Length of Initialized String is: "<<my_str.size() << endl;
    return 0;
}

In the above-given code:

  • Initially, we have added the necessary header files.
  • Then, inside the “main()” function we have declared a string variable “my_str” and initialized it.
  • Next, we called the “size()” function underneath the “cout” statement.

Output

Find String Length Using Using “length()” Function in C++

The “length()” function is also the built-in function in C++ and works the same as the “size()” function. It is utilized for finding the string length and returns counted characters in the provided string. Here is the example code for calculating the length of a string by using this function:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
 string my_str = "This is Tutorial Website";
 int len = my_str.length();
 cout << "Initialized String Length is: "<< len << endl;
     return 0;
}

The description of the above-given code block is:

  • First, we have added the necessary header files at the top of the code file.
  • After that, inside the “main()” function we have declared a string variable “my_str” and initialized it.
  • Then, we invoked the “length()” function with the input string and passed them to the integer type “len” variable.
  • Lastly, we used the “cout” statement to get the resultant value.

According to the following output, the length of the input string is “24”:

How to Find Length of String With User-defined Function in C++?

Another approach for calculating the length of the string is using the user-defined function that requires computing all characters present in the string through the loop when it reaches the “\0” null character which indicates that we have reached the end of the given string. To get a more clear idea check out the following example code:

#include <iostream>
#include <string>
using namespace std;

int mystrLen(string str)
{
  int x = 0;
  while (str[x] != '\0') x++;
  return x;
}

int main()
{
  string my_str;
  cout << "Please Enter Your String: ";
  getline(cin, my_str);
  cout << "The Length of Entered String is: " << mystrLen(my_str) << endl;
  return 0;
}

Here:

  • First of all, we added the required header files.
  • Then, we defined the user-defined function named “mystrLen”. Inside this function, we initialized the integer variable with the value “0”.
  • Next, iterate through the individual character of the string using the “while” loop to find the length of a provided input string. Along with it, we specified the “\0” null character as a condition.
  • Afterward, underneath the “main()” function we initialized a string type variable and added a “cout” stream for taking input from users.
  • Then, added the “getline()” built-in function to accept and read the single as well as multiple lines from the input stream.
  • At last, we used the “cout” statement to print the output on the console.

The provided output will be retrieved after executing the above-described code:

Use C Library Function in C++ to Find String Length

Another efficient way to calculate the length of the string is using the “strlen()” function that is extracted from the “<cstring>” header file. That is the C-Library function that returns the total number of characters in the string that is passed as an argument. Take the following example to get the length of a C-style string in C++:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char my_str[] = "LinuxHint World";
  cout << "The Length of String is: " << strlen(my_str) << endl;
  return 0;
}

According to the above code:

  • Initially, we have declared the necessary header files.
  • After that, we declared the character type array variable “my_str[ ]” and initialized it.
  • Next, we used the “strlen()” function with the input array variable to find the required value.

Output

How to Find String Length Using Loops in C++?

Users can also compute the length of the string in C++ without using the function. To do so, the iteration approaches can be used, that are:

  • for Loop 
  • while Loop

for Loop

In C++, for loop can be utilized for getting string length. An iterative variable that will traverse with the string length. In addition, the counter variable will be incremented by each iteration and the loop will be ended once the iterating variable reaches the null character. Here is the code for finding string length using the “for” loop in C++:

#include <iostream>
#include <string>
using namespace std;

int main() {

string myStr = "Welcome to LinuxHint";
int strLength = 0;

for (int x = 0; myStr[x] !='\0'; x++)
{
  strLength++;
}
  cout << "String: " << myStr << endl;
  cout << "Length of String: " << strLength << endl;
  return 0;
}

The explanation of the previously given code is:

  • First, we declared and initialized a string variable “myStr“.
  • Then, we added the integer type variable “strLength“ and initialized it with the value “0”.
  • Afterward, we used the “for” loop and specified the starting point, along with the “\0” null character condition and increment operator.
  • Next, we used the output stream to get the result on screen

Here is the output of the above-given code:

while Loop

The “while” loop is also used for getting string length. It is similar to the “for” loop, however, the only change is that it is used instead of the “for” loop. Let’s check out the provided example that is same as the previously described:

#include <iostream>
#include <string>
using namespace std;

int main() {

string inputStr = "LinuxHint";
int strLength = 0;

while (inputStr[strLength] != '\0')
{
  strLength++;
}

  cout << "Input String is: " << inputStr << endl;
  cout << "Length of String is: " << strLength << endl;
  return 0;
}

Output

How to Find Length of String Using Pointers in C++?

Let’s take another example by using the pointers approach that is used for the same purpose as we have discussed in the above examples. By using this approach, we will initialize the address of the first character of a string to a pointer type variable known as “ptr” and this variable will be utilized for finding the string length. As follows:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    char my_str[50], *ptr;
    int length=0;
    cout<<"Enter Input String: ";
    cin.getline(my_str, 50);
    ptr = &my_str[0];
    while(*ptr != '\0')
    {
    length++;
    ptr++;
    }
    cout << "The Length of Input String is: " << length << endl;
    return 0;
}

The output produced by this above program is:

How to Find Length of String Using Recursive Method in C++?

To compute the length of the input string in C++, the recursive method is also efficient. Recursion is the technique of creating a function call itself which offers a way to break complex programming problems and convert in to simple problems that are easier to solve:

#include<iostream>
#include<string>
using namespace std;

int mystrLen(string str)
{
 if (str == "")
   {
    return 0;
   }
 else {
    return 1 + mystrLen(str.substr(1)); }
}

int main() {
 string my_str = "LinuxHint World!!";
 int length = mystrLen(my_str);
 cout << "The Length of Input String is: " <<  length << endl;
 return 0;
}

Output

That’s all about getting the length of a string in C++ by using multiple approaches.

Bottom Line

In C++, the string is the set of characters enclosed between double quotes and represented as an array of characters followed by a null character at the end. With the help of a string, users can perform comparison, concatenation, conversion, and many more. In C++, there are multiple ways to get the length of the string, such as by using the built-in functions, user-defined functions, C Library functions, loops, pointers, and recursive(if-else) method. In this tutorial, we have described the various ways of finding the length of a string in C++.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.