-
Notifications
You must be signed in to change notification settings - Fork 1
1.2 Substrings
RobStewart edited this page May 15, 2013
·
1 revision
Accessing substrings is quite easy with std::string
, using the substr()
member function. In this example, hello
contains the five characters, hello
:
std::string text("Hello world!");
std::string hello(text.substr(0, 5));
Here's the signature of substr()
:
std::string
std::string::substr(std::size_t offset, std::size_t length = std::string::npos)
std::string::npos
is described in the Introduction. The default means to include the rest of the string.
Note that substr()
returns a new string. To modify a substring, in situ, use std::string::replace()
or std::string::insert()
.
Here's an example of replacing car
with bus
in the How many will fit in that car?
:
std::string text("How many will fit in that car?");
text.replace(26, 3, "bus");
replace()
has many overloads. Refer to pages like this and this for details.