字符串类的FindInclude(查找字符串是否包含在一个字符集中的字符)的实现优化...

以下是coremail的cyt所写的实现代码:
int IString::FindInclude(const char * pscCharSet,int nBegin) const
{
if (nBegin>m_length) nBegin=m_length;

int p;
for (;*pscCharSet!='\0';pscCharSet++)
{
p=this->Find(*pscCharSet,nBegin);
if (p!=-1) return p;
}
return -1;
}

是否没优化余地了呢? 非也,我在离开coremail之后,在自己重新实现字符串类的时候在mozilla的代码中找到了同样功能的代码并移植过来了:
static char GetFindInSetFilter(const char *set)
{
// Calculate filter
char filter = ~char(0); // All bits set
while (*set)
{
filter &= ~(*set);
++set;
}

return filter;
}

int TStr::FindCharInSet( const char* aCharSet,int nBegin) const
{
if ( nBegin<0 )
nBegin = 0;
if ( *aCharSet && nBegin>length )
{
// Build filter that will be used to filter out characters with
// bits that none of the terminal chars have. This works very well
// because searches are often done for chars with only the last
// 4-6 bits set and normal ascii letters have bit 7 set. Other
// letters have even higher bits set.

// Calculate filter
char filter = GetFindInSetFilter(aCharSet);

const char* endChar = str + length;
for (char *charp = str + nBegin; charp < endChar; ++charp)
{
char currentChar = *charp;
// Check if all bits are in the required area
if (currentChar & filter)
{
// They were not. Go on with the next char.
continue;
}
// Test all chars
const char *charInSet = aCharSet;
char setChar = *charInSet;
while (setChar)
{
if (setChar == currentChar)
{
// Found it!
return charp - str; // The index of the found char
}
setChar = *(++charInSet);
}
} // end for all chars in the string
}
return -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值