Introduction
The std::string class in C++ is designed to resolve the complexity and dangers associated with C-style char arrays, allowing you to handle strings safely and intuitively. You can perform various operations with natural syntax, just like basic data types such as int or double. In this article, I will explain the following four basic operations that are essential for mastering std::string, along with sample code.
- Input/Output:
cin/cout - Assignment:
= - Concatenation:
+ - Comparison:
==,!=,<,>, etc.
1. Input/Output
std::string objects can be easily input and output using standard I/O streams (cin, cout) and the >> / << operators.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "名前を入力してください: ";
cin >> name; // Reads until a space is encountered
cout << "こんにちは、" << name << "さん!" << endl;
return 0;
}
2. Assignment
You can use = (the assignment operator) to set a new string to a string object or copy the contents of another string object.
#include <iostream>
#include <string>
#include <utility> // move
using namespace std;
int main() {
string text1;
text1 = "Hello"; // Assigning a string literal
string text2 = text1; // Copying the content of text1 to text2
string temp_text = "World";
string text3 = move(temp_text); // C++11 and later: Move assignment
cout << "text1: " << text1 << endl;
cout << "text2: " << text2 << endl;
cout << "text3: " << text3 << endl;
return 0;
}
3. Concatenation
You can easily concatenate strings using + (the addition operator) or += (the compound assignment operator).
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Modern";
string str2 = " C++";
// Concatenation with + operator
string combined = str1 + str2; // -> "Modern C++"
// Can also concatenate with string literals or chars
combined = combined + " is powerful.";
// Appending with += operator
combined += "!!";
cout << combined << endl;
return 0;
}
4. Comparison
You can compare std::string objects lexicographically (in dictionary order) using comparison operators (==, !=, <, >, <=, >=).
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "apple";
string s2 = "orange";
string s3 = "apple";
cout << boolalpha; // Display bool as true/false
cout << s1 << " == " << s3 << " -> " << (s1 == s3) << endl; // true
cout << s1 << " != " << s2 << " -> " << (s1 != s2) << endl; // true
cout << s1 << " < " << s2 << " -> " << (s1 < s2) << endl; // true ('a' < 'o' in dictionary order)
return 0;
}
Explanation: String comparison is performed lexicographically based on the character codes, starting from the first character.
Summary
In this article, I explained the four most basic operations in C++ std::string: Input/Output, Assignment, Concatenation, and Comparison. Since these operators are appropriately overloaded in std::string, you can handle strings safely with an intuitive and simple syntax, almost identical to built-in numeric types.
