Welcome! In this lesson, we'll delve into the basic string manipulation features of C++, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations.
The idea behind stringstream is to treat strings as streams. This way, we can perform input/output operations on strings just as we do with cin and cout. Stringstreams are very useful for parsing strings. Consider the following example:
In the example above, we first declare a stringstream object ss
. We then insert the string "Hello World!" into this object using the insertion operator <<
. Then we declare a string hello
and extract a portion of the string from ss
into hello
using the extraction operator >>
. This operation sees a whitespace ' ' as the delimiter by default. So hello
will get "Hello".
The same operation is performed for world
, so world
will get "World!".
The output of the code is:
In C++, we can use a combination of std::istringstream
and std::getline
to tokenize a string, essentially splitting it into smaller parts or 'tokens'.
In the example above, we use a space as a delimiter to split the sentence
into words. This operation will print each word in the sentence on a new line.
In C++, the +
operator or the append()
function can concatenate strings into a larger string:
In the example above, we use +
and append()
to construct a larger string from smaller strings.
In C++, the std::ws
manipulator can remove leading spaces from a string. However, to remove trailing spaces, no standard library function exists. Hence, we have to write a custom function to accomplish this:
In this example, we use the std::ws
manipulator to remove leading whitespaces, and a custom function rtrim()
to remove trailing whitespaces from a string.
We can convert strings to numbers using functions like std::stoi
(string to integer) and std::stof
(string to float), and other data types to strings using std::to_string
:
In this code, we use std::stoi
, std::stof
, and std::to_string
for type conversions.
In some cases, we may need to combine all the methods discussed:
By integrating these methods, we can transform the string "1,2,3,4,6" into a vector of integers, calculate their average, and display the result.
Great job! You've gained an overview of C++'s string manipulation features, including string concatenation, string tokenization, trimming whitespace from strings, and type conversions. Now, it's time to get hands-on with these concepts in the exercises that follow. Happy coding!
