The std::string
class in C++ is part of the Standard Library and provides a high-level, convenient way to handle strings. It's defined in the <string>
header.
You can declare and initialize std::string
in several ways:
std::string str1; // Empty string
std::string str2 = "Hello"; // Initialization with a C-style string
std::string str3("World"); // Initialization using constructor
std::string str4 = str2; // Copy initialization
std::string str5(5, 'a'); // Initialize with 5 'a' characters ("aaaaa")
You can concatenate strings using the +
and +=
operators or the append()
method:
str1 = str2 + " " + str3; // "Hello World"
str1 += "!";
str1.append(" How are you?");
You can get the length of the string using length()
or size()
:
size_t len = str1.length();
You can also check the capacity and resize the string:
size_t cap = str1.capacity();
str1.resize(50);
You can access individual characters using the []
operator or the at()
method:
char firstChar = str1[0];
char secondChar = str1.at(1);
To get a substring, you can use the substr()
method:
std::string sub = str1.substr(0, 5); // Gets first 5 characters
To find a substring or a character, you can use find()
:
size_t pos = str1.find("World"); // Returns position or std::string::npos if not found
You can compare strings using relational operators (==
, !=
, <
, >
, etc.) or the compare()
method:
if (str1 == str2) {
// Strings are equal
}
To convert a std::string
to a C-style string, you can use the c_str()
method:
const char* cstr = str1.c_str();
To convert numbers to strings or vice versa, you can use std::to_string()
and std::stoi()
:
std::string numStr = std::to_string(42);
int num = std::stoi("42");
Integer (std::stoi
, std::stol
, std::stoll
): Convert to int
, long
, or long long
.
int i = std::stoi("42");
long l = std::stol("42");
long long ll = std::stoll("42");
Floating-Point (std::stof
, std::stod
, std::stold
): Convert to float
, double
, or long double
.
float f = std::stof("42.42");
double d = std::stod("42.42");
long double ld = std::stold("42.42");
Unsigned Integer (std::stoul
, std::stoull
): Convert to unsigned long
or unsigned long long
.
unsigned long ul = std::stoul("42");
unsigned long long ull = std::stoull("42");
You can iterate through a string using iterators or range-based for loops:
for (char c : str1) {
// Do something with c
}
std::string
manages memory automatically, resizing as needed.
Unlike strings in some other languages, std::string
objects are mutable. You can change them after they are created.
string()
: Default constructorstring(const string& str)
: Copy constructorstring(const char* s)
: Construct from a C-stringstring(size_t n, char c)
: Construct by repeating a charactern
times
operator[]
: Access elementat()
: Access element, throws out_of_range exception for invalid indexfront()
: Access the first characterback()
: Access the last character
append()
: Append to stringpush_back()
: Append a character to the endinsert()
: Insert into stringerase()
: Erase a part of stringreplace()
: Replace a part of stringswap()
: Swap content with another stringpop_back()
: Removes the last characterclear()
: Clears the content
size() / length()
: Return lengthempty()
: Check if string is emptyresize()
: Change sizereserve()
: Reserve storagecapacity()
: Get capacityshrink_to_fit()
: Shrink to fit
c_str()
: Get C string equivalentdata()
: Get array of characterscopy()
: Copy substring to C-arrayfind()
: Find substringrfind()
: Reverse findfind_first_of()
: Find character from setfind_last_of()
: Find last character from setfind_first_not_of()
: Find character not in setfind_last_not_of()
: Find last character not in setsubstr()
: Generate a substringcompare()
: Compare strings
operator+
: Concatenate stringsoperator+=
: Append to stringoperator== / operator!=
: Compare equality/inequalityoperator< / operator<= / operator> / operator>=
: Lexicographical compare