Skip to content
Branch: master
Go to file
Code

Latest commit

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 

README.md

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

Releases

No releases published

Languages

You can’t perform that action at this time.