Helpers.hpp 1.87 KB
Newer Older
aggsol's avatar
aggsol committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*
 Copyright (C) 2018  Kim HOANG <foss@aggsol.de>
 This file is part of gamebook-checker.

 xollox is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BODHI_HELPERS_HPP
#define BODHI_HELPERS_HPP

#include <random>

namespace bodhi
{
    /*
    * Returns an int from range [min, max]
    */
    template<class URNG>
    inline int randint(URNG& generator, int min, int max)
    {
        std::uniform_int_distribution<int> distribution(min, max);
        return distribution(generator);
    }

    /*
    *
    * Taken from: https://stackoverflow.com/questions/4643512/replace-substring-with-another-substring-c
    */
aggsol's avatar
aggsol committed
39 40
    inline std::string replaceSubStr(std::string& str, const std::string& target,
    const std::string& sub)
aggsol's avatar
aggsol committed
41
    {
aggsol's avatar
aggsol committed
42 43 44 45 46
        if(target == sub || target.empty())
        {
            return str;
        }

aggsol's avatar
aggsol committed
47 48 49 50 51 52 53 54 55 56 57
        size_t index = 0;
        while (true)
        {
             /* Locate the substring to replace. */
             index = str.find(target, index);
             if (index == std::string::npos)
             {
                 break;
             }

             /* Make the replacement. */
aggsol's avatar
aggsol committed
58
             str.replace(index, target.size(), sub);
aggsol's avatar
aggsol committed
59 60 61 62 63 64 65 66 67

             /* Advance index forward so the next iteration doesn't pick it up as well. */
             index += sub.size();
        }
        return str;
    }
}

#endif