aboutsummaryrefslogtreecommitdiff
path: root/src/StringUtils.cpp
blob: 16d3b48d82cd2f5f7d90b76d7778b6232b80cfaa (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
#include "../include/StringUtils.hpp"

namespace QuickMedia {
    void string_split(const std::string &str, char delimiter, StringSplitCallback callback_func) {
        size_t index = 0;
        while(true) {
            size_t new_index = str.find(delimiter, index);
            if(new_index == std::string::npos)
                break;

            if(!callback_func(str.data() + index, new_index - index))
                break;

            index = new_index + 1;
        }
    }

    void string_replace_all(std::string &str, const std::string &old_str, const std::string &new_str) {
        size_t index = 0;
        while(true) {
            index = str.find(old_str, index);
            if(index == std::string::npos)
                return;
            str.replace(index, old_str.size(), new_str);
        }
    }

    static bool is_whitespace(char c) {
        return c == ' ' || c == '\n' || c == '\t' || c == '\v';
    }

    std::string strip(const std::string &str) {
        if(str.empty())
            return str;

        int start = 0;
        for(; start < (int)str.size(); ++start) {
            if(!is_whitespace(str[start]))
                break;
        }

        int end = str.size() - 1;
        for(; end >= start; --end) {
            if(!is_whitespace(str[end]))
                break;
        }

        return str.substr(start, end - start + 1);
    }
}