C++ - Strings
In C++, strings are represented using the std::string class from the Standard Template Library (STL). Here are some common operations and features related to strings:
String Concatenation:
To concatenate (join) two strings together, you can use the + operator or the += operator.
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2; // Using the + operator
std::cout << result << std::endl; // Output: "Hello World"
Adding Numbers and Strings:
In C++, you can add a number to a string by converting the number to a string using std::to_string().
int num = 42;
std::string str = "The answer is: " + std::to_string(num);
std::cout << str << std::endl; // Output: "The answer is: 42"
String Length:
You can obtain the length (number of characters) of a string using the length() or size() member functions of std::string.
std::string str = "Hello";
std::cout << "Length of the string: " << str.length() << std::endl; // Output: 5
Access Strings:
You can access individual characters within a string using the indexing operator []. The index starts from 0.
std::string str = "Hello";
char firstChar = str[0]; // Accessing the first character
std::cout << "First character: " << firstChar << std::endl; // Output: 'H'
Strings - Special Characters:
Strings can contain special characters, such as newline (\n), tab (\t), double quote (\"), single quote (\'), backslash (\\), etc.
std::string str = "Hello\nWorld";
std::cout << str << std::endl; // Output:
// Hello
// World
The special characters are represented using escape sequences.