CPlusPlus / Strings#
What is string concatenation? How do you perform string concatenation in C++?
String concatenation is the operation of combining two or more strings to create a single, longer string. In C++, there are several ways to perform string concatenation:
With the + operator: This is the most straightforward method for std::string objects.
std::string str1 = "Hello"; std::string str2 = "World"; std::string result = str1 + " " + str2; // result is "Hello World"
Using the append() method:
std::string str1 = "Hello"; str1.append(" World"); // str1 is now "Hello World"
Using the += operator:
std::string str1 = "Hello"; str1 += " World"; // str1 is now "Hello World"
How do you find a substring within a string?
Using the find() method. Example: str.find(“substring”)
What’s the purpose of the capacity() method?
It returns the number of characters that the string can hold without requiring reallocation.
How do you convert a string to an integer?
Using the std::stoi() function. Example: int num = std::stoi(str)
What’s the difference between push_back() and append() for std::string?
push_back() adds a single character, while append() can add multiple characters or another string.
What’s the difference between erase() and clear() for std::string?
erase() can remove a portion of the string, while clear() removes all characters.