区分大小写的字符串替换
一个函数,用于替换另一个字符串中所有出现的字符串,忽略大小写
引言
这是一个简单的函数,它的作用类似于CString::Replace()
,只是在搜索字符串时忽略大小写。
完整的代码如下
// instr: string to search in.
// oldstr: string to search for, ignoring the case.
// newstr: string replacing the occurrences of oldstr.
CString ReplaceNoCase( LPCTSTR instr, LPCTSTR oldstr, LPCTSTR newstr )
{
CString output( instr );
// lowercase-versions to search in.
CString input_lower( instr );
CString oldone_lower( oldstr );
input_lower.MakeLower();
oldone_lower.MakeLower();
// search in the lowercase versions,
// replace in the original-case version.
int pos=0;
while ( (pos=input_lower.Find(oldone_lower,pos))!=-1 ) {
// need for empty "newstr" cases.
input_lower.Delete( pos, lstrlen(oldstr) );
input_lower.Insert( pos, newstr );
// actually replace.
output.Delete( pos, lstrlen(oldstr) );
output.Insert( pos, newstr );
}
return output;
}
该函数的实现非常简单:它创建了多个字符串的副本。如果您需要一个内存和速度优化的替换函数,那么这个可能不是最好的选择。无论如何,在我的项目中,它工作得很好。
如果您有任何问题,请随时通过电子邮件提问:keim@zeta-software.de。
历史
- 2000年1月25日:初始发布