C++ String Length

In C++, you can measure the number of characters in a string using the length() function. This comes in handy when working with text-based data, as it lets you evaluate the size of a string.

Tutorials dojo strip



Getting the Length of a String

The length() function is used to determine the number of characters in a string, including spaces, symbols, and punctuation.

Example

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

int main() {
    string bikeModel = "Kawasaki Ninja ZX-10R";
    cout << "The length of the bikeModel string is: " << bikeModel.length();

    return 0;
}

Output:
This outputs the length of the text “Kawasaki Ninja ZX-10R”, which includes the spaces between words.




Using the size() Function

C++ also provides the size() function, which works exactly the same as length(). The two are interchangeable, so you can use whichever feels natural to you.

Example

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

int main() {
    string carBrand = "Porsche 911 Turbo S";
    cout << "The length of the carBrand string is: " << carBrand.size();

    return 0;
}
Tutorials dojo strip
Scroll to Top