为什么 TrimRight 从字符串的开头搜索?
Why is TrimRight searching from the beginning of the string?
当我仔细检查一些代码时,这差点让我绊倒,我想知道我错过了什么。
下面是TrimRight
的实现方式(来自VS2005 MFC):
// Remove all trailing occurrences of character 'chTarget'
CStringT& TrimRight( __in XCHAR chTarget )
{
// find beginning of trailing matches
// by starting at beginning (DBCS aware)
PCXSTR psz = GetString();
PCXSTR pszLast = NULL;
while( *psz != 0 )
{
if( *psz == chTarget )
{
if( pszLast == NULL )
{
pszLast = psz;
}
}
else
{
pszLast = NULL; // Note: any other char resets search pos
}
psz = StringTraits::CharNext( psz );
}
if( pszLast != NULL )
{
// truncate at left-most matching character
....
这个实现看起来很奇怪。从字符串末尾开始搜索不是更自然(也更快)吗?
我认为@Angew 的评论是正确的:
starting at beginning (DBCS aware)
psz = StringTraits::CharNext( psz );
此函数必须正确处理多字节字符集,因此它必须向前扫描才能正确识别多宽度字符。
当我仔细检查一些代码时,这差点让我绊倒,我想知道我错过了什么。
下面是TrimRight
的实现方式(来自VS2005 MFC):
// Remove all trailing occurrences of character 'chTarget'
CStringT& TrimRight( __in XCHAR chTarget )
{
// find beginning of trailing matches
// by starting at beginning (DBCS aware)
PCXSTR psz = GetString();
PCXSTR pszLast = NULL;
while( *psz != 0 )
{
if( *psz == chTarget )
{
if( pszLast == NULL )
{
pszLast = psz;
}
}
else
{
pszLast = NULL; // Note: any other char resets search pos
}
psz = StringTraits::CharNext( psz );
}
if( pszLast != NULL )
{
// truncate at left-most matching character
....
这个实现看起来很奇怪。从字符串末尾开始搜索不是更自然(也更快)吗?
我认为@Angew 的评论是正确的:
starting at beginning (DBCS aware)
psz = StringTraits::CharNext( psz );
此函数必须正确处理多字节字符集,因此它必须向前扫描才能正确识别多宽度字符。