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++
#include<iostream>
#include<sstream>

int main(){
    std::stringstream ss;
    ss << "Hello World!";
    std::string hello;
    ss >> hello;
    std::cout << hello << std::endl;
    
    std::string world;
    ss >> world;
    std::cout << world << std::endl;
    
    return 0;
}

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:

Hello
World!

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++
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string sentence = "C++ is an amazing language!";
    std::istringstream sstream(sentence);
    std::string buffer;
    
    while (std::getline(sstream, buffer, ' ')) {
        std::cout << buffer << std::endl;
    }
    
    return 0;
}

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++
#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello,";
    std::string str2 = " World!";
    std::string greeting = str1 + str2;
    std::cout << greeting << std::endl;  // Output: "Hello, World!"
    
    std::string str3 = " C++ is fun.";
    greeting.append(str3);
    std::cout << greeting << std::endl;  // Output: "Hello, World! C++ is fun."
    
    return 0;
}

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

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal