Lesson 5

C++ String Manipulation and Type Conversion Essentials

Lesson Overview

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.

Understanding Stringstreams

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:

C++
1#include<iostream> 2#include<sstream> 3 4int main(){ 5 std::stringstream ss; 6 ss << "Hello World!"; 7 std::string hello; 8 ss >> hello; 9 std::cout << hello << std::endl; 10 11 std::string world; 12 ss >> world; 13 std::cout << world << std::endl; 14 15 return 0; 16}

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:

1Hello 2World!
Tokenizing a String in C++

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'.

C++
1#include <iostream> 2#include <sstream> 3#include <string> 4 5int main() { 6 std::string sentence = "C++ is an amazing language!"; 7 std::istringstream sstream(sentence); 8 std::string buffer; 9 10 while (std::getline(sstream, buffer, ' ')) { 11 std::cout << buffer << std::endl; 12 } 13 14 return 0; 15}

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.

Exploring String Concatenation

In C++, the + operator or the append() function can concatenate strings into a larger string:

C++
1#include <iostream> 2#include <string> 3 4int main() { 5 std::string str1 = "Hello,"; 6 std::string str2 = " World!"; 7 std::string greeting = str1 + str2; 8 std::cout << greeting << std::endl; // Output: "Hello, World!" 9 10 std::string str3 = " C++ is fun."; 11 greeting.append(str3); 12 std::cout << greeting << std::endl; // Output: "Hello, World! C++ is fun." 13 14 return 0; 15}

In the example above, we use + and append() to construct a larger string from smaller strings.

Trimming Whitespaces from 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:

C++
1#include <iostream> 2#include <string> 3#include <sstream> 4 5std::string rtrim(std::string str) { 6 while(str.size() && isspace(str.back())) str.pop_back(); 7 return str; 8} 9 10int main() { 11 std::string str = " Hello, World! "; // string with leading and trailing spaces 12 std::istringstream sstream(str); 13 std::getline(sstream >> std::ws, str); // remove leading spaces 14 str = rtrim(str); // remove trailing spaces 15 std::cout << str << std::endl; // Output: "Hello, World!" 16 17 return 0; 18}

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.

C++ Type Conversions

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:

C++
1#include <iostream> 2#include <string> 3 4int main() { 5 std::string num_str = "123"; 6 int num = std::stoi(num_str); 7 std::cout << num << std::endl; // Output: 123 8 9 std::string float_str = "3.14"; 10 float pi = std::stof(float_str); 11 std::cout << pi << std::endl; // Output: 3.14 12 13 int age = 20; 14 std::string age_str = std::to_string(age); 15 std::cout << "I am " << age_str << " years old." << std::endl; // Output: I am 20 years old. 16 17 return 0; 18}

In this code, we use std::stoi, std::stof, and std::to_string for type conversions.

Integrating String Tokenization, Concatenation, Trimming, and Type Conversions

In some cases, we may need to combine all the methods discussed:

C++
1#include <iostream> 2#include <string> 3#include <sstream> 4#include <vector> 5 6std::vector<int> split(const std::string &s, char delimiter) { 7 std::vector<int> tokens; 8 std::string token; 9 std::istringstream tokenStream(s); 10 while (std::getline(tokenStream, token, delimiter)) { 11 tokens.push_back(std::stoi(token)); 12 } 13 return tokens; 14} 15 16int main() { 17 std::string numbers = "1,2,3,4,6"; 18 std::vector<int> num_vector = split(numbers, ','); 19 int sum = 0; 20 for(auto num: num_vector) 21 sum+=num; 22 float average = static_cast<float>(sum) / num_vector.size(); 23 std::cout << "The average is " << average << std::endl; // Output: The average is 3.2 24 25 return 0; 26}

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.

Quick Recap and Next Steps

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!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.