字符串类的创建(下)
Posted 为了财务自由!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串类的创建(下)相关的知识,希望对你有一定的参考价值。
//非const就用&,因为可以出现在赋值号左边
char& String::operator[] (int i)
if((0<=i) && (i<m_length))
return m_str[i];
else
THROW_EXCEPTION(IndexOutOfBoundsException,"Parameter i is invalid...\\n");
char String::operator[] (int i)const
return (const_cast<String&>(*this))[i];
bool String::equal(const char* l,const char* r,int len)const
bool ret = true;
for(int i=0;i<len && ret;i++)
ret = ret && (l[i] == r[i]);
return ret;
bool String::startWith(const char* s)const
bool ret = (s != NULL);
if(ret)
int len = strlen(s);
ret = (len < m_length) && equal(m_str,s,len);
return ret;
bool String::startWith(const String& s)const
return startWith(s.m_str);
bool String::endOf(const char* s)const
bool ret = (s != NULL);
if(ret)
int len = strlen(s);
char* str = m_str + (m_length-len);
ret = (len < m_length) && equal(str,s,len);
return ret;
bool String::endOf(const String& s)const
return endOf(s.m_str);
String& String::insert(int i,const char* s)
if((0<=i) && (i<=m_length))
if((s != NULL) && (s[0]!='\\0'))
int len = strlen(s);
char* str = reinterpret_cast<char*>(malloc(m_length+len+1));
if(str != NULL)
strncpy(str,m_str,i);
strncpy(str+i,s,len);
strncpy(str+i+len,m_str+i,m_length-i);
str[m_length+len]='\\0';
free(m_str);
m_str=str;
m_length=m_length+len;
else
THROW_EXCEPTION(NoEnoughMemoryException,"No memory to insert string value...\\n");
else
THROW_EXCEPTION(IndexOutOfBoundsException,"Parameter i is invalid...\\n");
return *this;
String& String::insert(int i,const String& s)
return insert(i,s.m_str);
String& String::trim()
int b=0;
int e=m_length-1;
while(m_str[b] == ' ')b++;
while(m_str[e] == ' ')e--;
if(b == 0)//前面没空格
m_str[e+1] = '\\0';
m_length = e+1;
else
for(int i=0,j=b;j<=e;i++,j++)
m_str[i] = m_str[j];
m_str[e-b+1] = '\\0';
m_length=e-b+1;
return *this;
以上是关于字符串类的创建(下)的主要内容,如果未能解决你的问题,请参考以下文章
[C#][代码收集] - StringBuilder类的使用总结