为什么 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 );
此函数必须与多字节字符集一起正常工作,因此它必须向前扫描以正确识别多宽度字符。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- 按边长度递归搜索图中所有可行路径
- 搜索以特定字母开头的名称的所有匹配项
- 为什么 TrimRight 从字符串的开头搜索