What is a C++ string?
A string in C++ is an ordered sequence of characters.
There are three possible ways to create a sequence of characters in C++, a ‘string’ is just one of these ways:
- A simple array of characters is just like any other array; but it has no special properties that other arrays may have.
- A null terminated string, also called a
C-string, consists of an array of characters terminated by the null character ‘\0’. Strings of these forms can be created and dealt with using<cstring>library. Note that the null character may not be the last character in the C-string array.
- A
C++ stringis an object that is a part of the C++ standard library. It is an instance of a “class” data type, used for convenient manipulation of sequences of characters. To use the string class in your program, the<string>header must be included. The standard library string class can be accessed through the std namespace.
C++ strings provide a great deal of functionality and usability to the programmer. Despite the fact that all the tasks you might want to, theoretically,perform on a string can also be performed using C-strings; it’s generally far more convenient and intuitive to just use C++ strings.
Some functions for dealing with C++ strings and C-Strings are shown in the codes below:
Printing a String
#include <iostream>#include <string>using namespace std;int main() {string myStr = "Hello"; //initilizationcout << myStr << endl; //printingreturn 0;}
Calculate Length of a String
#include <iostream>#include <string>using namespace std;int main() {string myStr = "Hello"; //initilization//calculate lengthcout << "myStr's length is " << myStr.length() << endl;cout << "myStr's size is " << myStr.size() << endl;return 0;}
Concatenating two Strings
#include <iostream>#include <string>using namespace std;int main() {string myStr1 = "Hello"; //initilizationstring myStr2 = "World";//string concatenationstring myStr3 = myStr1 + myStr2;cout << "myStr1 + myStr2 = " << myStr3 << endl;return 0;}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved