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