This tutorial will discuss about a unique way to get length of a string in C++.
The string class in C++, provides a function size()
i.e.
std::size_t std::string::size() const
It returns the number of characters in the string. But,It does not includes the count of null-terminating character.
For example, if our string is “Sample Text”, like this,
std::string strValue = "Sample Text";
Then the strValue.size()
will return the value 11
as the size, which is the number of characters in the string.
Let’s see the complete example,
#include <iostream> #include <string> int main() { std::string strValue = "Sample Text"; // Get number of characters in string size_t len = strValue.size(); std::cout << "Length of the string is: " << len << "\n"; return 0; }
Output :
Frequently Asked:
- Get Char from String by Index in C++
- Convert a character to lowercase in C++
- Find all occurrences of a sub string in a string | C++ | Both Case Sensitive & InSensitive
- Check if a string is a number in C++
Length of the string is: 11
Summary
Today we learned about several ways to get length of a string in C++. Thanks.