C++ String size()

Video Tutorial
FREE
String Length thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate
Topics Covered

String size() function in C++ takes no parameter and returns the size of the string in terms of bytes which is how many characters it holds. This function is the public member function of the string class and finds the size of the string in constant time.

Syntax

Let the string variable of which we want to find the size be 'str'. The syntax will look like this:

String size in C++ function doesn't take any parameter and returns the number of bytes in the string and return value data type is an unsigned integral type that is size_t.

Return Value

The return value of the C++ size() function is an unsigned integer representing the number of characters (or the length) of the string. This function returns a std::string::size_type value, indicating the size of the string, which includes all characters, spaces, and special characters. It is a convenient way to determine the length of a string object in C++.

Exceptions

The string size() function in C++ doesn’t throw any error with the variable of a string data type, but if you try string size in C++ function with another primitive data type like int, char, etc., then it will throw an error. For example:

Output:

In the above example, we are trying to use this function on the “int” variable, due to which we got the error, and we should use this function with STL containers only.

Example

Let's create a string variable “str” and try to figure out its size using string size() in the C++ function.

Output:

In the above code, we created a string variable, got its size by using string size in C++ function, and stored it in an integer variable. At last, we printed it.

Conclusion

  • String size() in the C++ function takes no parameter and returns the size of the string in terms of bytes which is how many characters it holds.
  • String size() in C++ takes constant time to give the result.
  • String length() in C++ is similar function to string size() in c++, both returns the size of provided string.
  • This function counts all the characters, symbols, and whitespaces in the string.