remove space in string c++

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, world! This is a C++ string.";
    for (int i = 0; i < str.length(); ++i) {
        if (str[i] == ' ') {
            str.erase(i, 1);
            i--;
        }
    }
    cout << str << endl;
    return 0;
}