×

How to calculate size of string in C++

What is string in C++?

In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the <string> header. The std::string class provides a convenient and efficient way to manipulate strings in C++.

How to calculate size of string

There are some methods that helps us to calculate the size or we can say length of the string in C++ programming language.

Methods are as follows:

  • Length()
  • Strlen()
  • Size
  • Using loops

Using string::size

The length of a std::string object can be calculated using the .size() method of the std::string class.

The .size() method returns the number of characters stored in the std::string object, not including the null terminator.

Let’s understand with an example how we use string::size method in C++.

Example:

//program to calculate length or size of string using size method in C++
#include <iostream>
#include <string>
//main function of the program
int main() {
std::stringmyString = "Hello, My Name is Rohit Kumar";
int size = myString.size();
std::cout<< "The size of the string is: " << size <<std::endl;
return 0;
}

Output:

The size of the string is: 29

Explanation:

In this example, a std::string object named myString is declared and initialized with the string "Hello, My Name is Rohit Kumar". The .size() method is then used to calculate the size of the string and the result is stored in the size variable. Finally, the value of size is printed to the console using cout.

Note that the size() method  returns an unsigned integer value of type  std::string::size_type so you may need to cast the result  to a signed integer type, such as int  if you need  to store it in a signed integer variable.

Using string::length

Basically in C++, we can also calculate the size of the string using the .length() method of the std::string class. The length() method also return the number of the character stored in a string, not including the null character.

It is an alias for the .size() method, and both methods produce the same result.

Let’s understand with an example how we use string::length method in C++.

Example:

// program to calculate length or size of string using length method 
#include <iostream>
#include <string>
int main() {
std::stringmyDemo = "My name is Rohit Kumar and I am an intern in JTP";
int length = myDemo.length();
std::cout<< "The size of the string is: " << length <<std::endl;
return 0;
}

Output:

The size of the string is: 47

Explanation:

In this example, we named our string object as MyDemo and initialized it with the string “My name is Rohit Kumar and I am an intern in JTP”. With the help of the length() method, we calculated the size of the string and store the size of the string in the variable name size. Finally, the value of size is printed to the console using cout.

Using loops

You can calculate the size of a string using a loop in C++ by iterating over the characters in the string until you reach the null terminator (\0) character.

Here is an example using a C style string:

#include <iostream>
using namespace std;
int main() {
charmyString[] = "Good Morning My name is Akash Singh";
int size = 0;
for (inti = 0; myString[i] != '\0'; ++i) {
    ++size;
  }
std::cout<< "The size of the string is: " << size <<std::endl;
return 0;
}

Output:

The size of the string is: 35

Explanation:

In this example, a for loop is used to iterate over the characters in the string myString. The loop continues until the current character is the null terminator (\0). For each iteration of the loop, the value of size is incremented by 1. When the loop terminates, the value of size is equal to the size of the string.

Some advantages of string methods

There are several advantages to using the .size() or .length() methods to calculate the size of a std::string object in C++:

  • Convenience: The .size() or .length() methods provide a convenient way to get the length of a std::string object, without having to manually count the number of characters or use any additional functions.
  • Accuracy: The .size() or .length() methods are accurate and reliable, and return the correct length of the std::string object, even if the string contains special characters or Unicode characters.
  • Dynamic sizing: The std::string class is dynamically sized, so the length of a std::string object can change during the lifetime of the object. The .size() or .length() methods always return the current size of the std::string object, so you can use them to keep track of the size of the string even as it changes.
  • Portability: The .size() or .length() methods are part of the std::string class, which is part of the Standard Template Library (STL), so they are portable and can be used with any C++ compiler that supports the STL.

Related Topics

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.