StringStream in C++

In this tutorial, we will see how to use stringstream in C++ and understand by seeing some examples.

In C++, we have string stream, which allows string to be taken as a stream, which helps us to perform insertion and deletion operations on a string.

Removing spaces using stringstream

Let’s see how to remove spaces in a string using stringstream.

#include <bits/stdc++.h>
using namespace std;

int main(){

    string a = "Hello world, let's see how to use stringstream in cpp";
    string word;

    stringstream ss (a);
    
    while(ss >> word)
        cout << word << endl;

    return 0;
}

Output

Hello
world,
let's
see
how
to
use
stringstream
in
cpp

 

Removing commas using stringstream

Let’s see how to remove commas in a string using stringstream

#include <bits/stdc++.h>
using namespace std;

int main(){

    string a = "Hello world, hello, world, hi";
    string word;

    cout << "Before: " << a << endl;

    stringstream ss (a);

    cout << "After: ";
    while(getline(ss, word, ',')){
        cout << word;
    }

    return 0;
}

Output

Before: Hello world, hello, world, hi
After: Hello world hello world hi

 

Likewise, you can remove any delimiter using stringstream. In line 14, change ‘,’ to any delimiter.

Also read: string::npos in C++

Leave a Reply

Your email address will not be published.