C++ provides the std::string
class for handling and manipulating strings. Here are some common operations you can perform with strings:
Initialization:
std::string str1 = "Hello";
std::string str2("World");
std::string str3;
Concatenation:
std::string str4 = str1 + " " + str2; // "Hello World"
Accessing Characters:
char c = str1[1]; // 'e'
Length:
size_t len = str1.length(); // 5
Substrings:
std::string substr = str1.substr(1, 3); // "ell"
Finding Substrings:
size_t pos = str1.find("lo"); // 3
Comparison:
if (str1 == "Hello") {
// Do something
}
Modification:
str1[0] = 'h'; // "hello"
getline
is used to read an entire line of text from an input stream, which is useful for processing input that contains spaces.
Basic Usage:
std::string input;
std::getline(std::cin, input);
With Custom Delimiter:
std::string input;
std::getline(std::cin, input, ','); // Reads until a comma is encountered
For Loop Input:
string s;
int t;cin>>t;
cin.ignore(); // to ignore the '\\n' from the first line after taking the input t;
while(t--){
cin>>s;
}
C++'s native data types (int
, long
, etc.) have size limitations, so handling very large numbers requires special techniques or libraries.
Storing Big Numbers as Strings:
std::string bigNum1 = "12345678901234567890";
std::string bigNum2 = "98765432109876543210";