OneBite.Dev - Coding blog in a bite size

Count A String Length In C++

Code snippet for how to Count A String Length In C++ with sample and detail explanation

At times, programming requires you to find out the length (number of characters) of a string in C++. Whether you’re sorting strings in a database or parsing text input for a video game, understanding how to count a string length can be a critical skill. In C++, we can do this quickly, and in this article, we’ll show you how it’s done.

Code Snippet: How to Count a String Length in C++

#include <iostream>
#include <string>
using namespace std;
  
int main() {
   string myString = "Hello, world!";
   cout << "The length of the string is: " << myString.length();
   return 0;
}

Code Explanation for How to Count a String Length in C++

The #include <iostream> and #include <string> lines at the beginning of the code are preprocessor directives that tell the compiler to include the iostream and string libraries in the program. The iostream library allows us to use cin and cout for user input and output respectively, and the string library allows us to use the string data type.

The line using namespace std; is a directive that tells the compiler to use the standard (std) namespace. A namespace is like a container that holds a set of identifiers, helping to avoid name collisions in larger programs.

In the main function, we first declare and define a string named ‘myString’ with the content “Hello, world!“.

The cout line then prints out a sentence that tells us the length of the string. In C++, the string length can be found using the .length() function directly on the string variable, which is myString.length() in this case. The length function counts the number of characters in the string, including spaces and punctuation, and returns that number. So, in this program, the output will be “The length of the string is: 13” because there are 13 characters in the string “Hello, world!” including the comma, space, and exclamation mark.

Conclusively, the above code is a simple way of counting the length of a string in C++. With it, you can easily determine the number of characters in a string.

c-plus-plus