Datatype string

Data types specify whether the data are numbers (integer, double float), characters (char), strings (string), truth values (boolean), or other.
Strings consist of words, characters, digits, or a combination thereof, delimited from program code by double apostrophes.

The length of a string is the number of characters it consists of. The individual characters of a string of length n are numbered from 0 to n-1. As an alternative to strings, you could also work with arrays of characters.

Syntax

    string s;
    string str1 = "Hello World";
    string str2(10, '-');
    string str3("Hello World");

C++ String Methods

Code Explanation

LineDescription
1Include <iostream> header that defines the standard input / output stream objects
2Namespaces allow to group entities like classes, objects and functions under a name. It contains all components of the standard library of C++
4Declaration of the main() function with the return value int
5Creates a new variable named str1 of datatype string with the value “Hello”
6Creates a new variable named str2 of datatype string with the value “World”
7Creates a new variable called str3. The value of this variable is the concatenation of str1 and str2
9Prints the merged string str3
10Different methods can be called via an object of a string. The append() method appends one list to another
11The length() method outputs the length of a list
12The at() method returns the element of the list at the specified index
13The insert() method adds a new element to the list at the specified index
15Returns the value 0, because the main() function expects a return value of type int
#include &lt;iostream&gt;
using namespace std;

int main(){
    string str1 = "Hello";
    string str2 = "World";
    string str3 = str1 + " " + str2;

    cout << str3 << endl;
    cout << "append: " << str1.append(str2) << endl;
    cout << "length: " << str1.length() << endl;
    cout << "at: " << str1.at(3) << endl;
    cout << "insert: " << str1.insert(2, "l") << endl;

    return 0;
}
Output
Hello World
append: HelloWorld
length: 10
at: l
insert: HellloWorld