我的C++常用函数

发布时间 2023-04-26 13:50:51作者: 小鼬就是我
/* 根据多个分隔符来分隔字符串. 比如 " :,]" */
std::vector<std::string> SplitString(const std::string& str, const std::string& delimiters) {
    std::vector<std::string> tokens;
    size_t prev = 0, pos;
    while ((pos = str.find_first_of(delimiters, prev)) != std::string::npos) {
        if (pos > prev) {
            tokens.push_back(str.substr(prev, pos-prev));
        }
        prev = pos + 1;
    }
    if (prev < str.length()) {
        tokens.push_back(str.substr(prev, std::string::npos));
    }
    return tokens;
}

static std::string Trim(std::string source)
{
        std::replace( source.begin(), source.end(), '\t', ' '); // replace all '\t' to ' '
        std::replace( source.begin(), source.end(), '\n', ' ');
        std::replace( source.begin(), source.end(), '\r', ' ');

    std::string result = source.erase(source.find_last_not_of(" ") + 1);
    return result.erase(0, result.find_first_not_of(" "));
}

static double Stod(std::string s) {
    std::string ss = Trim(s);
    //return ss.empty() ? 0.0 : std::stod(ss);
    return ss.empty() ? 0.0 : std::atof(ss.c_str());
}

static int Stoi(std::string s) {
    std::string ss = Trim(s);
    return ss.empty() ? 0 : std::stoi(ss);
}

static std::string get_curr_format_hhmmss() { // eg: 09:30:00
    time_t t = time(NULL); 
    struct tm *p = localtime(&t);
    char s[64];
    strftime(s, sizeof(s), "%H:%M:%S", p);
    return std::string(s);
}