Skip to content

C++ class to split a string into pieces by given delimiters.

Notifications You must be signed in to change notification settings

Allidylls/StringSpliter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 

Repository files navigation

StringSpliter

C++ class to split a string into pieces by given delimiters, a wrapper of c_tokenizer.

string_spliter.h

/* string_spliter.h */

#pragma once
#ifndef STRING_SPLITER_H
#define STRING_SPLITER_H

class StringSpliter {
public:
    enum {EMPTIES_OK = 0, NO_EMPTIES};

public:
    StringSpliter(const char* str, const char* delimiters, int empties = StringSpliter::EMPTIES_OK);
    ~StringSpliter();
    const char* Next();

private:
    char*       m_string;
    const char* m_delimiters;
    char*       m_current;
    char*       m_next;
    bool        m_is_ignore_empties;
};

#endif

string_spliter.cpp

/* string_spliter.cpp */

#include <string>
#include "string_spliter.h"

StringSpliter::StringSpliter(const char* str, const char* delimiters, int empties)
{
    if (str && delimiters) {
        size_t n = strlen(str) + 1;
        char  *p = (char*)malloc(n);
        if (p) {
            this->m_string = (char*)memcpy(p, str, n);
        } else {
            this->m_string = NULL;
        }
    } else {
        this->m_string = NULL;
    }
    this->m_delimiters        = delimiters;
    this->m_current           = NULL;
    this->m_next              = this->m_string;
    this->m_is_ignore_empties = (empties != StringSpliter::EMPTIES_OK);
}

StringSpliter::~StringSpliter()
{
    free(this->m_string);
    this->m_string = NULL;
}

const char* StringSpliter::Next()
{
    if (!this->m_string || !this->m_next) {
        return NULL;
    }

    this->m_current = this->m_next;
    this->m_next = strpbrk(this->m_current, this->m_delimiters);

    if (this->m_next) {
        *(this->m_next) = '\0';
        this->m_next += 1;
        if (this->m_is_ignore_empties) {
            this->m_next += strspn(this->m_next, this->m_delimiters);
            if (!(*(this->m_current))) {
                return this->Next();
            }
        }
    } else if (this->m_is_ignore_empties && !(*(this->m_current))) {
        return NULL;
    }

    return this->m_current;
}

Usage

char *str = "$PTNL,PJK,102823.80,012613,+3541087.713,N,+1878282.023,E,1,16,0.8,EHT+52.668,M*4F";
StringSpliter string_spliter(str, ",");
int n;
const char *sec;
for (n=0, sec = string_spliter.Next(); sec; sec=string_spliter.Next(), n++) {
    printf("%2d: %s\n", n, sec);
}

About

C++ class to split a string into pieces by given delimiters.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages