gpt4 book ai didi

c++ - 为什么 TrimRight 从字符串的开头搜索?

转载 作者:行者123 更新时间:2023-11-30 05:46:08 25 4
gpt4 key购买 nike

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

这是如何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 );

此函数必须正确处理多字节字符集,因此它必须向前扫描才能正确识别多宽度字符。

关于c++ - 为什么 TrimRight 从字符串的开头搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29072832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com