Strings in C++
String are the data types which are collection of characters. In order to use strings library should be included in the header. Strings are inside the double quotes. Two strings can be added together with ‘+‘ operator and append( ) function. This is called string concatenation. The length( ) or size( ) function can be used to get the length of the strings.
The characters of a string can be accessed with its index number. The following program shows first and fifth character of the string str. push_back( ) function is used to insert a character at the end of the string. pop_back( ) function is used to delete last character from a string. A string character can be changed by using its index number. getline( ) function is used to takes the entire character of the string. It takes cin as first parameter and the string variable as a second parameter.
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "Hello world";
cout<<str<<"\n";
// Concatenation
string first = "One dozen";
string second = " banana";
cout<<first+second<<"\n";
string newStr = first.append(second);
cout<< newStr<<"\n";
// Length of a string
cout<<"The length of a string is "<<str.length()<<"\n";
cout<<"The size of the string is "<<str.size()<<"\n";
// Access the character of string
cout<< str[0]<<"\n";
cout<< str[4]<<"\n";
str.push_back('s');
cout<<"The string is "<<str<<"\n";
str.pop_back();
cout<<"The string after using pop_back() function is "<<str<<"\n";
// Changing a string character
string str2 = "Abcd";
str2[2]='f';
cout<<str2<<"\n";
// Use of getline() function
string str3;
cout<<"Write a string ";
getline(cin, str3);
cout<<"The entered string is "<<str3;
return 0;
}
Output:
Hello world
One dozen banana
One dozen banana
The length of a string is 11
The size of the string is 11
H
o
The string is Hello worlds
The string after using pop_back() function is Hello world
Abfd
Write a string This is a string example
The entered string is This is a string example