Sunday, August 31, 2014

How To: Missing String Related Functions in C++ - Replace, Split, Trim etc.

String manipulation functions are really important and we often find ourselves needing them while coding in C++. High-level languages like C# and Java etc. provide such functions through methods of a string class. However, they are not inherently present in C++.

Here are some of the more frequently used string related functions. They are pretty self-explanatory. All of them are independent functions. Hope you find them useful.

Note: Don't forget to include the appropriate headers: <string> <vector> <sstream>

using namespace std;

string strToLowerCase(string str) {

    const int length = str.length();
    for(int i=0; i < length; ++i) {
        str[i] = tolower(str[i]);
    }
    return str;
}

string strToUpperCase(string str) {

    const int length = str.length();
    for(int i=0; i < length; ++i) {
        str[i] = toupper(str[i]);
    }
    return str;
}

void strReplace(string &str, const string what, const string to) {

    if (str.empty() || what.empty()) return;

    size_t pos;
    while ( (pos = str.find(what)) != string::npos ) {
        str.replace(pos, what.length(), to);
    }
}

vector<string> strSplit(string s, char delim) {
    vector<string> elems;
    stringstream ss(s);
    string item;
    while(getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

string strTrim(string str) {

    size_t pos1 = str.find_first_not_of(" \t");
    size_t pos2 = str.find_last_not_of(" \t");

    str = str.substr(pos1 == string::npos ? 0 : pos1,
        pos2 == string::npos ? 0 : pos2 - pos1 + 1);

    return str;
}

bool strStartsWith(string str, string start) {

    if (start.length() > str.length()) return false;
    if ( str.substr(0, start.length()) == start ) return true;
    else return false;
}

bool strEndsWith(string str, string end) {

    if (end.length() > str.length()) return false;
    if ( str.substr(str.length() - end.length()) == end ) return true;
    else return false;
}

int strCountWords(string str) {

    int count = 0;
    for (int i=0; i < str.length(); i++) {
        if (isspace(str.at(i))) count++;
    }
    return (count+1);
}


0 comments:

Post a Comment