为什么 TrimRight 从字符串的开头搜索

Why is TrimRight searching from the beginning of the string?

本文关键字:开头 搜索 字符串 TrimRight 为什么      更新时间:2023-10-16

当我仔细检查一些代码时,这几乎绊倒了我,我想知道我错过了什么。

以下是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 );

此函数必须与多字节字符集一起正常工作,因此它必须向前扫描以正确识别多宽度字符。