C++. Реализация функции strtok

571
08 марта 2017, 20:22

Нужна собственная реализация этой функции. Немогу ничего грамотного реализовать. Может быть у кого то есть какой то пример этой функции.

Answer 1

Велосипедный вариант:

bool schar(const string& str, const char& op)
{
    auto it = str.cbegin();
    while (it != str.cend()) {
        if (*it == op) return true;
        it++;
    }
    return false;
}
string smerge(string::const_iterator& it1,string::const_iterator& it2,const string& delim)
{
    string ss;
    while (it1 != it2) {
        if (!schar(delim,*it1))
            ss += *it1;
        it1++;
    }
    return ss;
}
vector<string> stoken(const string& str,const string& delim)
{
    auto it1 = str.cbegin();
    auto it2 = str.cbegin();
    vector<string> vec;
    while (it2 != str.cend()) {
        if (schar(delim, *it2)) {
            string s = smerge(it1, it2, delim);
            if(s.size()) {
                vec.push_back(s);
            }
        }
        it2++;
    }
    vec.push_back(smerge(it1, it2, delim));
    return vec;
}
Answer 2

Ну, например, так - просто и незатейливо:

char * mystrtok(char * str, const char * delim)
{
    static char * last = 0;
    if (str) last = str;
    if ((last == 0) || (*last == 0)) return 0;
    char * c = last;
    while(strchr(delim,*c)) ++c;
    if (*c == 0) return 0;
    char * start = c;
    while(*c && (strchr(delim,*c)==0)) ++c;
    if (*c == 0)
    {
        last = c;
        return start;
    }
    *c = 0;
    last = c+1;
    return start;
}
Answer 3

Можно взять и посмотреть внутри glibc

  • https://github.com/lattera/glibc/blob/master/string/strtok.c
  • http://www.retro11.de/ouxr/211bsd/usr/src/lib/libc/string/strtok.c.html
  • https://opensource.apple.com/source/Libc/Libc-186/string.subproj/strtok.c
READ ALSO
Приведение числовых типов через reinterpret_cast

Приведение числовых типов через reinterpret_cast

Если мы используем reinterpret_cast для приведения указателя к указателю, объекта к указателю или указателя к объекту, то приведение осуществляется...

225
Другая компоновка в классе-потомке

Другая компоновка в классе-потомке

ЗдравствуйтеЕсть класс ComparisionTable, наследуемый от QWidget с виджетами: два QLabel и один QTableWidget

199