/** 字符串规范比较 */
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <string>
#include <locale.h>
#include <algorithm>
#define G_STR_ALL _T("english:AbCdEfG;汉字: 一二三四五 符号: !=~")
//#define G_STR_OBJ1 _T("cDe") //ok, find it
#define G_STR_OBJ1 _T(";汉字")
#ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
#define ERR_STR_NOT_FIND tstring::npos
/** tstring to 小写 */
TCHAR tchar2lower(TCHAR c);
/**
* @fn BOOL FindString(CONST TCHAR * pcSrc, CONST TCHAR * pcObj,
* size_t & posFind)
* @brief 在源串中寻找目标串, 支持中文和英文混写, 宽字符和ascii字符混写
* @param CONST TCHAR * pcSrc, 源串
* @param CONST TCHAR * pcObj, 目标串
* @param size_t & posFind, OUT 如果找到strObj, 返回strObj在strSrc的位置
* @return BOOL
* @retval TRUE, strSrc中包含strObj
* @retval FALSE, strSrc中不包含strObj
*/
BOOL FindString(CONST TCHAR * pcSrc, CONST TCHAR * pcObj, size_t & posFind);
int _tmain(int argc, _TCHAR* argv[])
{
tstring strSrc;
tstring strObj;
size_t posFind = ERR_STR_NOT_FIND;
_tsetlocale(LC_ALL, _T("Chinese_People's Republic of China.936"));
strSrc = G_STR_ALL;
strObj = G_STR_OBJ1;
if(FindString(strSrc.c_str(), strObj.c_str(), posFind))
{
_tprintf(_T("找到目标字串\n"));
}
/** run results
<strSrc>=<english:abcdefg;汉字: 一二三四五 符号: !=~>
<strObj>=<;汉字>
<posFind string>=<;汉字: 一二三四五 符号: !=~>
找到目标字串
*/
getchar();
return 0;
}
BOOL FindString(CONST TCHAR * pcSrc, CONST TCHAR * pcObj, size_t & posFind)
{
tstring strSrcCpy = pcSrc;
tstring strObjCpy = pcObj;
std::transform(strSrcCpy.begin(), strSrcCpy.end(), strSrcCpy.begin(),
tchar2lower);
std::transform(strObjCpy.begin(), strObjCpy.end(), strObjCpy.begin(),
tchar2lower);
posFind = strSrcCpy.find(strObjCpy);
_tprintf(_T("<%s>=<%s>\n"), _T("strSrc"), strSrcCpy.c_str());
_tprintf(_T("<%s>=<%s>\n"), _T("strObj"), strObjCpy.c_str());
if(ERR_STR_NOT_FIND != posFind)
{
_tprintf(_T("<%s>=<%s>\n"), _T("posFind string"),
strSrcCpy.c_str() + posFind);
}
/** 串比较的规范方法 tstring::npos */
return (ERR_STR_NOT_FIND != posFind) ? TRUE : FALSE;
}
TCHAR tchar2lower(TCHAR c)
{
return (c >= _T('A') && c <= _T('Z')) ? c -('Z'-'z') : c;
}