易辅 发表于 2016-9-9 11:33:28

寻找文本 易转 C++写法

该函数格式如下:
InStr( string1, string2[, compare])

start 可选参数。为数值表达式,设置每次搜索的起点。如果省略,将从第一个字符的位置开始。如果 start 包含 Null,将发生错误。如果指定了 compare 参数,则一定要有 start 参数。
string1 必要参数。接受搜索的字符串表达式。
string2 必要参数。被搜索的字符串表达式。
Compare 可选参数。指定字符串比较。如果 compare 是 Null,将发生错误。如果省略 compare,Option Compare 的设置将决定比较的类型。

在C++中也有类似的函数,比如strstr,strchr

但是这些函数都是从第一个字符进行比较的,而且返回是个指针。如果需要从一个长字符串中多次连续寻找指定的子串,就比较麻烦,所以我用C++编写了模仿instr功能的函数,通过重载实现了可选参数,以及一个区分大小写的标志,函数返回为位置整数而不是指针,与VB中不同的是,返回-1代表失败,0为字符串中第一个位置(C/C++风格)

下面是函数声明
int InStr(int iStart,LPSTR lpSourceString,LPSTR lpFindString,bool bFullMatch);
int InStr(int iStart,LPSTR lpSourceString, char FindChr,bool bFullMatch);
int InStr(LPSTR lpSourceString,LPSTR lpFindString);
int InStr(LPSTR lpSourceString, char FindChr);

函数实现

//在源字串中按匹配方式查找子串或字符,
//找到后返回数组下标,即所在串中的位置,0为第一个字符,
//不成功返回-1
//按字符串、匹配标志查找,
int InStr(int iStart,LPSTR lpSourceString,LPSTR lpFindString,bool bFullMatch)
{
int pos=-1,len1,len2,i,j,c;
char *tp,*fp,*p=NULL;
if (lpSourceString && lpFindString)
{
len1=strlen(lpSourceString);
len2=strlen(lpFindString);
if (len2 && iStart>=0 && len1>(len2+iStart))//判断字符长度是否有效
{
if (!bFullMatch || iStart)//不分大小写或者查询位置不是第一字符
{
//复制第一字符串
tp=new char;
if (tp)
{
tp=strcpy(tp,lpSourceString);
if (!bFullMatch)tp=strupr(tp); //如果不分大小写,转换所有字符为大写
}


fp=new char;//复制第二字符串
if (fp)
{
fp=strcpy(fp,lpSourceString);
if (!bFullMatch)fp=strupr(fp); //如果不分大小写,转换所有字符为大写
}

if (tp && fp)
{
for (i=iStart;i<=(len1-len2);i++)//从指定起点开始循环扫描
{
c=0;
for (j=0;j<len2;j++)//扫描一段字符串判断是否与要查找的字符串相等
{
if (tp==fp)c++;else break;
}
if (c==len2)//如果找到,设置返回值,结束循环
{
pos=i;break;
}
}
}
if (tp){delete []tp;tp=NULL;}
if (fp){delete []tp;tp=NULL;}
}
else//区分大小写且起点位置为第一字符
{
p=strstr(lpSourceString,lpFindString);
if(p)pos=p-lpSourceString;
}
}
}
p=NULL;
return (pos);
}
//重载InStr,按单个字符、匹配标志查找,
int InStr(int iStart,LPSTR lpSourceString, char FindChr,bool bFullMatch)
{
int pos=-1,length,i;
char *tp,*p=NULL;
if (lpSourceString)
{
length=strlen(lpSourceString);
if (iStart>=0 && length>iStart)//判断字符长度是否有效
{
if (!bFullMatch || iStart)//不分大小写或者查询位置不是第一字符
{
//复制第一字符串
tp=new char;
if (tp)
{
tp=strcpy(tp,lpSourceString);
if (!bFullMatch)
tp=strupr(tp); //如果不分大小写,转换所有字符为大写
if (FindChr>=0x41 && FindChr<=0x5A ||
FindChr>=0x61 && FindChr<=0x7A)
FindChr&=0xDf;
}

if (tp)
{
for (i=iStart;i<length;i++)//从指定起点开始循环扫描
{
if (tp==FindChr)
{pos=i;break;}
}
}
if (tp){delete []tp;tp=NULL;}
}
else//区分大小写且起点位置为第一字符
{
p=strchr(lpSourceString,FindChr);
if(p)pos=p-lpSourceString;
}
}
}
p=NULL;
return (pos);
}
//重载InStr,按字符串、不分大小写,从第一个字符查找
int InStr(LPSTR lpSourceString,LPSTR lpFindString)
{
return (InStr(0,lpSourceString,lpFindString,false));
}
//重载InStr,按单个字符、不分大小写从第一个字符查找
int InStr(LPSTR lpSourceString, char FindChr)
{
return (InStr(0,lpSourceString,FindChr,false));
}

hahayzl 发表于 2017-11-2 01:26:14

楼主超给力,易辅客栈真是难得给力的平台啊。
页: [1]
查看完整版本: 寻找文本 易转 C++写法