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");
#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
#include <iostream>
includes the iostream
library, which provides input and output functionality in C++.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
.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.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”.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”.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”.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”.return 0;
statement ends the main()
function and returns 0
to the operating system, indicating successful program execution.