The length or size of a string means the total number of characters present in it. For Example, The string “learnetutorials” has 15 characters. In this C++ program, we need to find the length of the string
C++ has length()
and size()
function. These can be used to get the length of a string-type object. This function is used to return the length of the string in terms of bytes. It gives the number of bytes aligned to form the string.
Syntax: Consider a string object named 'str'. To calculate the size of this string object, its syntax would be : str.size()
Parameters: This function does not contain any parameters.
Return Value: size() function returns the number of characters or the bytes in the string.
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Open the integer type main function; int main().
Step 4: Declare string type variable str = “welcome to learnetutorials”
Step 5: Get the length of the string by using the function str. length();
Step 6: Print the length of the string.
Step 7: Exit
#include <iostream>
using namespace std;
int main() {
string str = "Welcome to learnetutorials";
// you can also use str.size()
cout << "String Length = " << str.length();
return 0;
}
String Length = 26