loading...

C++ simple string operations

lucpattyn profile image Mukit, Ataul ・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;
}

//usage:

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.push_back(token);
}

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

Posted on by:

lucpattyn profile

Mukit, Ataul

@lucpattyn

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++

Discussion

pic
Editor guide