Labs ICT
โญ Pro Login

Strings

In C++, you have two ways to work with text. You can use C-style strings (arrays of characters), but honestly, do not bother with those. The modern C++ way is to use the string type from the standard library. It is easier, safer, and just better in every way.

Using the string Type

To use strings, you need #include <string>. After that, you can declare string variables just like any other type. Strings can be concatenated with + and you can get their length with .length().

#include <iostream>
#include <string>
using namespace std;

int main() {
  string greeting = "Hello";
  string name = "Bilal";
  string message = greeting + ", " + name + "!";

  cout << message << endl;
  cout << "Length: " << message.length() << " characters";
  return 0;
}

The + operator joins strings together. The .length() function returns how many characters are in the string, including spaces and punctuation. Strings are one of those things that just work in C++ once you know the basics.

๐Ÿงช Quick Quiz

Which header file do you need for C++ strings?