Avatar ·

How to replace all occurrences of a character in a string in C++? (std::string)

Hello everyone! I just started learning C++ and ran into a problem: I need to replace all spaces in a string with an underscore character. For example, I have the string "Hello World from C++". I want to get "Hello_World_from_C++".\n\nI know that in C# there is a `.Replace()` method that does this in one line. In Python there is also `str.replace()`. How do I do this in C++? I'm using `std::string`.\n\nI tried writing a loop, but it didn't work out. Here's my unsuccessful code:\n\n```cpp\n#include \n#include \n\nint main() {\n std::string str = "Hello World from C++";\n for (size_t i = 0; i < str.length(); i++) {\n if (str[i] == ' ') {\n str[i] = '_';\n }\n }\n std::cout << str << std::endl;\n return 0;\n}\n```\n\nThis code works, but it's very primitive.