Program Listing for File StringTools.hpp

Return to documentation for file (include/networkit/auxiliary/StringTools.hpp)

/*
 * StringTools.hpp
 *
 *  Completely rewritten on: 12.05.2014
 *      Author: Florian Weber (uagws@student.kit.edu)
 */

#ifndef NETWORKIT_AUXILIARY_STRING_TOOLS_HPP_
#define NETWORKIT_AUXILIARY_STRING_TOOLS_HPP_

#include <algorithm>
#include <string>
#include <string_view>
#include <vector>

namespace Aux {

namespace StringTools {

template <typename Iterator, typename Character>
std::vector<std::string> split(Iterator begin, Iterator end, Character delim = Character{' '}) {

    // measurements showed that precalculating the number of tokens and
    // reserving space for them was in fact slower than just letting
    // the vector grow naturally.
    std::vector<std::string> tokens;

    auto it = begin;
    while (it != end) {
        auto tmp = std::find(it, end, delim);
        tokens.emplace_back(it, tmp);
        if (tmp == end) {
            break;
        }
        it = tmp;
        ++it;
    }
    return tokens;
}

inline std::vector<std::string> split(std::string_view s, char delim = ' ') {
    return split(s.begin(), s.end(), delim);
}

inline bool ends_with(std::string_view str, std::string_view suffix) {
    return str.size() >= suffix.size()
           && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}

inline bool starts_with(std::string_view str, std::string_view prefix) {
    return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0;
}

} /* namespace StringTools */
} /* namespace Aux */
#endif // NETWORKIT_AUXILIARY_STRING_TOOLS_HPP_