Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Example
4.1.
C++
5.
Return Value
6.
Example 
6.1.
C++
7.
Example
7.1.
C++
7.2.
Explanation
7.3.
For C-style strings
8.
Frequently Asked Questions
8.1.
Is there a difference in performance between .length() and .size() for std::string?
8.2.
What happens if I use strlen on a non-null-terminated string?
8.3.
Can these methods be used to determine the size of strings containing Unicode characters?
9.
Conclusion 
Last Updated: Jun 9, 2024
Easy

String Length in C++

Author Ravi Khorwal
0 upvote

Introduction

Strings are a fundamental part of programming in C++. They allow us to store & manipulate text data in our programs. In C++, strings are managed in a way that allows for efficient performance and flexible manipulation.

String Length in C++

In this article we will learn how to find the length of a string using different methods & understand the importance of string length in various scenarios.We will also discuss the syntax of obtaining string length, the parameters involved, with an example.

Syntax

In C++, the length of a string can be determined using various methods depending on the type of string being used. For standard C++ strings (std::string), the .length() or .size() methods are commonly employed. Both methods return the number of characters in the string and are equally efficient. 

Let’s see the basic syntax : 

std::string myString = "Hello, World!";
std::cout << "Length of myString: " << myString.length() << std::endl;
std::cout << "Size of myString: " << myString.size() << std::endl;


For C-style strings, which are arrays of characters terminated by a null character ('\0'), the strlen function from the <cstring> library is used:

#include <cstring>
char myCString[] = "Hello, World!";
std::cout << "Length of myCString: " << strlen(myCString) << std::endl;

Parameters

When working with string length in C++, the methods and functions used typically do not require any parameters. Let’s see few of them below : 

  • std::string::length() or std::string::size(): These methods are part of the std::string class and do not require any parameters. They operate on the string instance from which they are called.

 

  • strlen(const char* s): This function is used for C-style strings. It takes a single parameter:

 

  • const char* s: A constant character pointer that points to the first character of a null-terminated C-style string.

Example

  • C++

C++

#include <iostream>

#include <cstring> // Required for strlen

int main() {

   // Using std::string

   std::string exampleString = "Example";

   std::cout << "Length of exampleString: " << exampleString.length() << std::endl;

   // Using C-style string

   const char* cStyleString = "Example";

   std::cout << "Length of cStyleString: " << strlen(cStyleString) << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Length of exampleString: 7
Length of cStyleString: 7


In this example, exampleString.length() is called without any arguments as it operates directly on the exampleString object. For strlen, the argument cStyleString is a pointer to the first character of the string, indicating where the function should start counting until it reaches the null terminator.

Return Value

The functions and methods used to determine the length of a string in C++ have clear and straightforward return values:

  • std::string::length() or std::string::size(): These methods return a value of type std::size_t. This type is an unsigned integral type and represents the number of characters in the string. The value indicates the actual count of characters present before the null terminator, not including the terminator itself.

 

  • strlen(const char* s): Similar to the methods for std::string, strlen returns a value of type size_t. This function counts the number of characters up to but not including the null terminator ('\0').

Example 

  • C++

C++

#include <iostream>

#include <cstring> // Required for strlen

int main() {

   std::string exampleString = "Hello, world!";

   std::cout << "Length of exampleString using .length(): " << exampleString.length() << std::endl;

   std::cout << "Length of exampleString using .size(): " << exampleString.size() << std::endl;

   const char* cStyleString = "Hello, world!";

   std::cout << "Length of cStyleString using strlen: " << strlen(cStyleString) << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Length of exampleString using .length(): 13
Length of exampleString using .size(): 13
Length of cStyleString using strlen: 13


In this code, all methods and functions report the number of characters in the string Hello, world!, which is 13. This includes spaces but excludes the null character at the end of the C-style string.

Example

Now let’s see a complete program using all the concepts we have learned before : 

Example Program: Calculate String Length

  • C++

C++

#include <iostream>

#include <cstring> // For strlen on C-style strings

int main() {

   // For std::string

   std::string userInput;

   std::cout << "Enter a string: ";

   getline(std::cin, userInput);

   std::cout << "Length of your string using std::string is: " << userInput.length() << std::endl;

  // For C-style string

   const int BUFFER_SIZE = 256;

   char cStyleInput[BUFFER_SIZE];

   std::cout << "Enter another string: ";

   std::cin.getline(cStyleInput, BUFFER_SIZE);

   std::cout << "Length of your string using C-style string is: " << strlen(cStyleInput) << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Enter a string: Hello
Length of your string using std::string is: 5
Enter another string: World
Length of your string using C-style string is: 5

Explanation

For std::string

  • The program prompts the user to enter a string. The getline(std::cin, userInput) function is used to read a line of text into a std::string object.
     
  • The .length() method of the std::string object userInput is then used to display the length of the string entered by the user.

For C-style strings

  • A character array cStyleInput with a buffer size of 256 characters is defined to store the C-style string.
     
  • The user is prompted again to enter a string. The std::cin.getline(cStyleInput, BUFFER_SIZE) function reads the line into the cStyleInput array.
     
  • The strlen function calculates the length of the C-style string, omitting the null terminator, and the result is displayed.

Frequently Asked Questions

Is there a difference in performance between .length() and .size() for std::string?

Both .length() and .size() methods of std::string perform identically in terms of speed and functionality, as they simply return the number of characters in the string.

What happens if I use strlen on a non-null-terminated string?

Using strlen on a string that is not null-terminated can lead to undefined behavior, including crashes, as strlen will continue to count characters until it encounters a null character.

Can these methods be used to determine the size of strings containing Unicode characters?

The methods .length() and .size() count the number of characters, not bytes. For UTF-8 encoded strings, this might not accurately reflect the number of visual characters. strlen also counts bytes until the null terminator, which might not correspond to character boundaries in UTF-8.

Conclusion 

In this article, we have learned how to determine the length of strings in C++ using standard methods for std::string and the strlen function for C-style strings. We also discussed the syntax, parameters, and return values associated with these methods and saw it’s practical example. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass