0
0
CppHow-ToBeginner · 3 min read

How to Find Length of String in C++: Simple Syntax & Example

In C++, you can find the length of a string using the length() or size() method on a std::string object. Both methods return the number of characters in the string as a size_t value.
📐

Syntax

To get the length of a string in C++, use the length() or size() method on a std::string object.

  • string.length(): Returns the number of characters in the string.
  • string.size(): Does the same as length(), interchangeable.
cpp
std::string str = "Hello";
size_t len = str.length();
💻

Example

This example shows how to create a string and print its length using length().

cpp
#include <iostream>
#include <string>

int main() {
    std::string greeting = "Hello, world!";
    std::cout << "The length of the string is: " << greeting.length() << std::endl;
    return 0;
}
Output
The length of the string is: 13
⚠️

Common Pitfalls

Some common mistakes when finding string length in C++ include:

  • Using strlen() on std::string objects, which is incorrect because strlen() works only with C-style strings (char*).
  • Confusing length() with the size of the buffer or capacity of the string.
  • Not including the <string> header, which is required for std::string.
cpp
#include <iostream>
#include <string>

int main() {
    std::string s = "Test";
    // Wrong: strlen(s.c_str()) - will work but is unnecessary
    // std::cout << strlen(s.c_str()) << std::endl;

    // Correct:
    std::cout << s.length() << std::endl;
    return 0;
}
Output
4
📊

Quick Reference

MethodDescription
string.length()Returns the number of characters in the string.
string.size()Same as length(), returns string length.
strlen(char*)Use only for C-style strings, not std::string.

Key Takeaways

Use std::string's length() or size() method to get string length in C++.
Do not use strlen() on std::string objects; it works only with C-style strings.
Both length() and size() return the number of characters as size_t.
Always include header when working with std::string.
length() does not count any null terminator, just visible characters.