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.
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
C++
x
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”, including spaces between words.
Using the size() Function
C++ also provides the size()
function, which works exactly the same as length()
. Both are interchangeable, so you can use whichever feels more natural to you.
Example
C++
using namespace std;
int main() {
string carBrand = "Porsche 911 Turbo S";
cout << "The length of the carBrand string is: " << carBrand.size();
return 0;
}