强大稳定的字符串分割 C++ 类:StringSpliter

jopen 5年前

一个强大稳定的字符串分割 C++ 类,是对 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;  }

用法:

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);  }

项目主页:http://www.open-open.com/lib/view/home/1404896001497