求助:带通配符字符串比较的问题

Sunbow_xlj 2002-03-29 01:58:55
请编程

比较两个字符串str1,str2,允许str2中存在通配符 “*”和“?”,
‘*’代表任意个字符;
‘?’代表一个字符。

例如 str1 = 111abcd2228000
str2 = 111*222*?000
那么 认为str1 等于 str2;
...全文
130 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
jishiping 2002-03-29
  • 打赏
  • 举报
回复
下面是我的程序适用的函数,包括对* 和 ?的处理。我用的好好的,
到目前还没有用户反映有问题。

BOOL IsStrMatched(LPCSTR Val, LPCSTR Match, int len)
{
int n;
int num;
bool ret;
LPCSTR s;

if (!Val || !Match)
return FALSE;
num = len<0 ? strlen(
Match) : len;
for(; *Match&# num-=n) {
if (*Match=='?') {
if (*Val=='\0')
return FALSE;
Match++; Val++;
n = 1; continue;
}
if (*Match != '*') {
if (*Match!=*Val)
return FALSE;
Match++; Val++;
n = 1; continue;
}
while(*Match=='*') {
num--; Match++;
if (num == 0)
return 1;
}
if (*Match=='\0')
return TRUE;
s = strchr(Match,'*');
if (s != NULL)
n = s - Match;
else
n = strlen(Match);
for(; *Val; Val++) {
if (IsStrMatched(
Val,Match,n))
break;
}
if (*Val == '\0')
return FALSE;
Match += n; Val += n;
}
return num==0 && (len>=0
|| *Val==0);
}
hcpp 2002-03-29
  • 打赏
  • 举报
回复
1.转化str2=111*222*?000
=>str2=111*222*000
2,分解str2=>
str2_temp1=111;
str2_temp2=222;
str2_temp3=000;
并将他们存入CstringArray strArray;
3.比较:
\\声明查找指针:pos;(指明当前str1查找的位置)
int pos=0;
int i=0;
if(pos=str1.find(strArray[i].[0],pos)==-1)
return false;

while( pos<str1.GetLength())
{

if(str1.Left(strArray[i].GetLength()).Compare(strArray[i])
==0)
{
if(i<strArray.GetLength())
{
pos+=strArray[i].GetLength();
i++;
}
else
{
if(pos<str1.GetLength())
return true;
else
return false;
}
}
else
return false;
if(pos=str1.find(strArray[i].[0],pos)==-1)
return false;

}
大概就是这样,我没有vc,没有调试,但我想应该没问题!









garfield_82 2002-03-29
  • 打赏
  • 举报
回复
不好意思,equal的初值应该为1
garfield_82 2002-03-29
  • 打赏
  • 举报
回复
# include <iostream>
# include <string>

using namespace std;

int main()
{
const char cAny = '*';
const char cOne = '?';

string string1, string2; // string2 can include tokens
int ix;
bool equal = 0;


cout << " Input String1 = ";
cin >> string1;
cout << " Input String2 ( can including '*' or '?') = ";
cin >> string2;

for ( ix = 0; ix < string2.size() ; ix ++ )
{
if ( string2 [ ix ] == cAny )
{
equal = 1;
break;
}

if ( string2 [ ix ] == cOne )
string2 [ ix ] = string1 [ ix ];

if ( string2 [ ix ] != string1 [ ix ] )
{
equal = 0;
break;
}
}

if ( equal == 1 )
cout << "Equal";
else
cout << "Not Equal";


return 0;
}

我写了一个,你看看
garfield_82 2002-03-29
  • 打赏
  • 举报
回复
同意freezingfire,你这样认为*是由问题的,因为如果*代表任意个字符,那么 111* == 111abcd2228000
freezingfire 2002-03-29
  • 打赏
  • 举报
回复
首先,你*的用法不对,*后面不可以再有字符,像你的用法会产生歧义。
如果只是?的话则非常容易了。

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧