Strings

Strings

String is a sequence of characters. String type is declared inside the <string> header and is part of the std namespace. A simple example:

#include <iostream>
#include <string>
int main(){
	std::string s = "Hello World!";
}

Here we declared a variable of type std::string and initialized with a value of "Hello World!". String literal is enclosed in double quotes: "Some string value". We can print out a string:

#include <iostream>
#include <string>
int main(){
	std::string s = "Hello World!";
	std::cout << s;
}

We can concatenate strings:

#include <iostream>
#include <string>
int main(){
	std::string s = "Hello";
	s = s + " World!";
	std::cout << s;
}

Similar:

#include <iostream>
#include <string>
int main(){
	std::string s1 = "Hello";
	std::string s2 = " World!";
	std::string s3 = s1 + s2;
	std::cout << 3;
}

String class has some useful helper functions like:

#include <iostream>
#include <string>
int main(){
	std::string s1 = "Hello World!";
	auto mysize = s1.size(); // returns the string size
	auto c = s1.at(5); // returns a single character with a index of 5
	s1.append(" Added to a string."); // appends a string
}