×

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

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 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.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.