DEV Community


C++ simple string operations

Mukit, Ataul
I consider myself as an enthusiast in learning new things everyday, about our history and future as well as the present. My interests: Ancient History, Comparative Religion, Science and Tech, C++
・1 min read

String Replace:

bool str_replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if (start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);

    return true;


std::string str = "John XXX";
str_replace(str, "XXX", "Doe");

String Tokenize:

std::string input = "We, are, all, strangers, here"; // our input
char delim = ','; // our delimiter

std::istringstream ss(input);
std::string token;

std::vector tokens;
while(std::getline(ss, token, delim)) {

// tokens contain the array of tokenized strings separated by delimiter 

Discussion (0)