×

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

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

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.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

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

4 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

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

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Diamond Pattern in C++ using For Loop

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

5 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.