c++ 實現的簡易字串類
#include
using
namespace std;
class
sstring
// 構造字元全部為ch,長度為count的字串
sstring
(const
char ch,
int count)
this
->m_ptrstr[
this
->m_nlength]
='\0';}
// 刪除所有字元chchar
bool
strdeletecharall
(const
char chchar)}if
(k ==
this
->m_nlength)
else
}// 刪除指定字元chchar
bool
strdeletechar
(const
char chchar)
this
->m_nlength -=1
;return
true;}
}return
false;}
// 建構函式
sstring
(const
char
* ptrstr)
this
->m_nlength = ptrstr - ptrtemp -1;
this
->m_ptrstr =
newchar
[this
->m_nlength +1]
;memset
(this
->m_ptrstr,0,
(this
->m_nlength +1)
*sizeof
(char))
;memcpy_s
(this
->m_ptrstr,
this
->m_nlength +
1, ptrtemp, ptrstr - ptrtemp);}
// 拷貝建構函式
sstring
(const sstring& str)
// 返回字串長度
intstrlength()
const
// 析構函式,用於釋放m_ptrstr動態分配的記憶體
virtual
~sstring()
this
->m_ptrstr =
null
;this
->m_nlength =0;
}// 刪除字串中[nleft,nright)的字元,nleft必須小於nright並且nright必須大於1
// 如果nleft小於1,則刪除[1,nright),如果nright>strlength,則刪除[nleft,strlength)
bool
deletebetween
(int nleft,
int nright)
if(nleft <=0)
if(nright >
this
->m_nlength +1)
int between = nright - nleft;
while
(nleft <=
this
->m_nlength)
this
->m_nlength -
= between;
return
true;}
// 擷取從npos開始的字元到npos+ncount的子串
const sstring&
substring
(int npos,
int ncount)
if(ncount >
(this
->m_nlength - npos +1)
|| ncount <0)
sstring* ptrsubstring =
newsstring()
; ptrsubstring-
>m_nlength =0;
ptrsubstring-
>m_ptrstr =
newchar
[ncount +1]
;memset
(ptrsubstring-
>m_ptrstr,
0, ncount +1)
;memcpy_s
(ptrsubstring-
>m_ptrstr, ncount,
this
->m_ptrstr + npos -
1, ncount)
; ptrsubstring-
>m_ptrstr[ncount]=0
; ptrsubstring-
>m_nlength = ncount;
return
*ptrsubstring;
}// 刪除指定位置的字元
bool
deleteposchar
(int i)
while
(i <=
this
->m_nlength)
this
->m_nlength -=1
;return
true;}
// 清空
void
strclear()
this
->m_nlength =0;
}// 銷毀字串
void
destory()
this
->m_nlength =0;
this
->m_ptrstr =
null;}
bool
strempty()
const
// 賦值運算子過載
const sstring&
operator=(
const sstring& str)
// 將字串str拼接到當前字串中
const sstring&
operator+(
const sstring& str)
this
->m_ptrstr = ptrtempstr;
this
->m_nlength = nsize -1;
return
*this;}
catch(.
..)}
// 獲取字串中第i個字元,i從0開始
char
operator
(int i)
const
const
char
*strdata()
const
// 查詢模式串substring與當前串的子串匹配所在的位置,-1表示不存在
intfindsubstring
(const sstring& substring)
const
else}if
(ptrnextvalue !=
null)if
(j > substring.m_nlength)
else
}protected
:// 獲取匹配陣列即nextval
void
getnextvalue
(int
*& ptrnextval)
const
else
}else}}
private
:char
* m_ptrstr;
int m_nlength;};
intmain
(void
)
C 字串類實現
c 字串類實現,包括預設建構函式,帶乙個引數的建構函式,copy建構函式,賦值運算,加法運算等 在vc6.0下編譯通過 by kvew www.atrix.org bbs www.secoder.org bbs main函式 include include strings.h using names...
C 字串類實現
c 字串類實現,包括預設建構函式,帶乙個引數的建構函式,copy建構函式,賦值運算,加法運算等 在vc6.0下編譯通過 by kvew www.atrix.org bbs www.secoder.org bbs main函式 include include strings.h using names...
c 字串類String的實現
include class string string string strobj string const char tostring int getlength string operator string strobj string operator char s string operato...