Open In App

std::string::size() in C++

Last Updated : 16 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::string::size() function in C++ is a built-in method of the std::string class that is used to determine the number of characters in the string. All characters up to the null character are considered while calculating the size of the string.

In this article, we will learn about string::size() method in C++.

Syntax

s.size()

where s is the string whose length is to be found.

Parameters

  • This function does not take any parameters.

Return Value

  • Returns the size of the string as an unsigned integer size_t.
  • If the string is empty, it returns 0.

Example of string::size()

C++
// C++ Program to demonstrate how to use string::size()
// to get the number of characters in a string
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s1 = "abcd";
  	string s2 = "";
  	string s3 = "#&&";

    // Getting the size of the strings
    cout << "String 1 Size: " << s1.size() << endl;
  	cout << "String 2 Size: " << s2.size() << endl;
  	cout << "String 3 Size: " << s3.size();
    return 0;
}

Output
String 1 Size: 4
String 2 Size: 0
String 3 Size: 3

Time Complexity: O(1)
Auxiliary Space: O(1)

Note: string::size() function only works with C++ Style strings i.e. std::string objects. For C-Style strings i.e. array of characters, use strlen() function.

Difference between string::size() and string::length()

There is no difference between the functions string::size() and string::length(). They both do the same task, have similar signature and can be used interchangeably. They are just there for consistency and people's preferences.


Next Article
Practice Tags :

Similar Reads