代碼不穩定,大俠幫看看
/*
参数:
szSrc 源字符串
szPattern 要查找的字符串
szDelimiter 分隔符表
ppFound 存放查找到的位置
nMaxFound ppFound的大小
返回值:
找到的符合条件的位置数
用法:
char *ppFound[100];
char *szDelimiter = " \t\r\n,.;+-'"[]{}()*&^%$#@!"; // 自定义分隔符表
int nFound = ExactlyMatch(szSrc, szPattern, szDelimiter, ppFound, 100);
*/
int ExactlyMatch(const char *szSrc, const char *szPattern, const char *szDelimiter,const char *ppFound[], int nMaxFound) {
const char *pchStart = NULL;
const char *pch = szSrc;
int nFound = 0;
while ( true ) {
bool bIsDelimiter = strchr(szDelimiter, *pch) || (*pch == '\0');
if ( bIsDelimiter ) {
if ( pchStart != NULL ) {
int len = pch - pchStart;
if ( strncmp(pchStart, szPattern, len) == 0 ) {
ppFound[nFound++] = pchStart;
if ( nFound == nMaxFound )
return -1;
}
}
pchStart = NULL;
} else {
if ( pchStart == NULL )
pchStart = pch;
}
if ( *pch++ == '\0' )
break;
}
return nFound;
}
大侠帮看看代码要如何改进,功能是精确查找.
[解决办法]
查了一下,这个函数有多查的问题,但没测出漏查,新改进的函数如下:
//---------------------------------------
/* 参数:
szSrc 源字符串
szPattern 要查找的字符串
szDelimiter 分隔符表
ppFound 存放查找到的位置
nMaxFound ppFound的大小
返回值: 找到的符合条件的位置数
-1表示数量超出ppFound的大小
用法:
char *ppFound[100];
char *szDelimiter = " \t\r\n,.;+-'"[]{}()*&^%$#@!"; // 自定义分隔符表
int nFound = ExactlyMatch(szSrc, szPattern, szDelimiter, ppFound, 100);
*/
int ExactlyMatch(const char *szSrc, const char *szPattern, const char *szDelimiter, const char *ppFound[], int nMaxFound) {
const char *pchStart = NULL;
const char *pch = szSrc;
int nFound = 0;
int nPatternLen = strlen(szPattern);
while ( true ) {
bool bIsDelimiter = strchr(szDelimiter, *pch)
[解决办法]
(*pch == '\0');
if ( bIsDelimiter ) {
if ( pchStart != NULL ) {
int len = pch - pchStart;
if ( len == nPatternLen && strncmp(pchStart, szPattern, len) == 0 ) {
ppFound[nFound++] = pchStart;
if ( nFound == nMaxFound )
return -1;
}
}
pchStart = NULL;
} else {
if ( pchStart == NULL )
pchStart = pch;
}
if ( *pch++ == '\0' )
break;
}
return nFound;
}