LarbinString類對象的實現
一 該類介紹
LarbinString類主要是字符串處理,主要的成員參數是 char * chaine 表示字符串的內容存儲的指針地址。
還有pos 表示當前string的位置,size表示最大的容量。
成員函數,都為一些添加字符,添加緩沖區的操作。其中的主要的是 recycle() ,getString() ,giveStirng()等函數。
二 類的頭文件
// Larbin
// Sebastien Ailleret
// 20-12-99 -> 05-05-01

#ifndef STRING_HH
#define STRING_HH

#include <assert.h>

#include "types.h"
#include "utils/debug.h"


class LarbinString
{
private :
char * chaine ; //內存指針
uint pos ; //當前位置
uint size ; //總共的大小
public :
//Constructor
LarbinString(uint size= STRING_SIZE) ;
~LarbinString() ;
//Recycle this string
void recycle(uint size=STRING_SIZE) ;
//get the char *
//it is deleted when you delete this Stringobject
char * getString() ;
//give a char * : it creates a new one
char * giveString();
//append a char
void addChar(char c) ;
//append a char *
void addString(char * s) ;
//append a buffer
void addBuffer(char * s , uint len) ;
//length of the string

inline uint getLength()
{return pos ;}
//get a char of this string
inline uint operator[] (uint i)

{
assert(i<=pos) ;
return chaine[i] ;
}
//change a char
void setChar(uint i , char c) ;




};

#endif // STRING_HH
三 實現代碼
該代碼實質上是實現了,一個string類型,可以自動地增長容量,實現動態地增添操作。
// Larbin
// Sebastien Ailleret
// 20-12-99 -> 10-12-01

#include <string.h>
#include <iostream>

#include "options.h"

#include "utils/text.h"
#include "utils/string.h"

using namespace std ;
// Constructor

LarbinString::LarbinString (uint size)
{
chaine = new char[size] ;
pos = 0 ;
this->size = size ;
chaine[0] = 0 ;
}

// Destructor

LarbinString::~LarbinString ()
{
delete [] chaine ;
}

// Recycle this string

void LarbinString::recycle (uint size)
{
if(this->size > size) //當大小小于當前的大小時

{
delete [] chaine ;
chaine = new char[size] ;
this->size = size ;
}
pos = 0 ;
chaine[0] = 0 ;
}

// get the char *

char *LarbinString::getString ()
{
return chaine ;
}


/**//** give a new string (allocate a new one
* the caller will have to delete it
*/

char *LarbinString::giveString ()
{
return newString(chaine) ;
}

// append a char

void LarbinString::addChar (char c)
{
chaine[pos] = c;
pos++ ;
if(pos >= size) //如果當前的

{
char * tmp = new char[2 * size] ;
memcpy(tmp , chaine , pos) ;
delete [] chaine ;
chaine = tmp ;
size *= 2 ;
}
chaine[pos] = 0 ;
}

// append a char *

void LarbinString::addString (char *s)
{
uint len = strlen(s);
addBuffer(s, len);
}

// append a buffer

void LarbinString::addBuffer (char *s, uint len)
{

if (size <= pos + len)
{
size *= 2;
if (size <= pos + len) size = pos + len + 1;
char *tmp = new char[size];
memcpy(tmp, chaine, pos);
delete [] chaine;
chaine = tmp;
}
memcpy(chaine+pos, s, len);
pos += len;
chaine[pos] = 0;
}

// change a char

void LarbinString::setChar (uint i, char c)
{
chaine[i] = c;
}
四 總結
LarbinString類主要進行的是字符串處理,實質上是自己實現了一個String庫。