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 Example

#include <iostream>
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

Code Explanation

  1. The line #include <iostream> includes the iostream library, which provides input and output functionality in C++.
  2. Inside the main() function, three string variables are declared and initialized:
    • str1, which is initialized with the string “Hello”.
    • str2, which is initialized with the string “World”.
    • str3, which is initialized by concatenating str1, a space character, and str2.
  3. The line cout << str3 << endl; uses the << operator to insert the value of str3 into the output stream, which will be displayed as “Hello World” on the console.
  4. The line cout << "append: " << str1.append(str2) << endl; demonstrates the append() method of the string class. It appends str2 to str1 and inserts the result into the output stream. The output will display “append: HelloWorld”.
  5. The line cout << "length: " << str1.length() << endl; demonstrates the length() method of the string class. It returns the length of str1 and inserts it into the output stream. The output will display “length: 10”.
  6. The line cout << "at: " << str1.at(3) << endl; demonstrates the at() method of the string class. It accesses the character at index 3 of str1 and inserts it into the output stream. The output will display “at: l”.
  7. The line cout << "insert: " << str1.insert(2, "l") << endl; demonstrates the insert() method of the string class. It inserts the string “l” at index 2 of str1 and inserts the modified string into the output stream. The output will display “insert: HellloWorld”.
  8. Finally, the return 0; statement ends the main() function and returns 0 to the operating system, indicating successful program execution.