关于字符串匹配问题

peterzhu1999 2003-08-11 10:35:52
写一个函数,实现如下功能:
在行字符串中
1 845,596,6954,9485,200,8845,00182,121
2 1234,567,8861,0404
输入一个字符串(数字),找到与之匹配的字符串的标记(要求前面一位一定匹配,才判断后面一位的是不是匹配)
如输入 8861234,则返回的是 2,输入8845212,返回则是 1,但是8843则算是没有匹配的。没有匹配的返回 -1
...全文
14 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
prettynacl 2003-08-11
  • 打赏
  • 举报
回复
不用这么复杂吧。

#include <stdio.h>
#define BUFLEN 1024
char dest[] = "845,596,6954,9485,200,8845,00182,121";

main()
{
char number[BUFLEN];
char *pos;
int numlen, destlen;

gets(number);
numlen = strlen(number);
destlen = strlen(dest);

pos = dest;
while(pos < dest + destlen) {
pos = (char*)strstr(pos, number);
if (pos == NULL) {
break;
}
if (pos + numlen >= dest + destlen){
printf("find it\n");
break;
}
if (*(pos + numlen) == ',') {
printf("find it\n");
break;
}
pos += numlen;
}
}
ejiue 2003-08-11
  • 打赏
  • 举报
回复
偶理解错了。
int nRow = 1;就能满足楼主的要求。
ejiue 2003-08-11
  • 打赏
  • 举报
回复
++nRow;这一句。
似乎应该放在for循环内。
ejiue 2003-08-11
  • 打赏
  • 举报
回复
RedSunRS(RedSun),佩服。
RedSunRS 2003-08-11
  • 打赏
  • 举报
回复
DEV-CPP , VC6, win2000 professional.
RedSunRS 2003-08-11
  • 打赏
  • 举报
回复
#include <iostream>
#include <stdlib.h>
#include <list>

using namespace std;

bool Compare( const char* pszKey, const char* pszComp )
{
assert( pszKey != NULL && pszComp != NULL );
cout << "comparing... " << pszKey << " " << pszComp << endl;
bool bEqual = true;
while( *pszKey != '\0' && *pszComp != '\0' && (bEqual = *pszKey++ == *pszComp++) );
if( *pszComp != '\0' )
return false;
else if( bEqual )
return true;
else
return false;
}

int CompInRows( const char* pszKey, list<list<char*>*>* rowlist )
{
assert( pszKey != NULL && rowlist != NULL );
int nRow = 0;
for( std::list<list<char*>*>::iterator it = rowlist->begin()
; it != rowlist->end(); ++it )
{

for( std::list<char*>::iterator pString = (*it)->begin()
; pString != (*it)->end(); ++pString )
{
if( Compare( pszKey, *pString ) )
return nRow;
}
++nRow;
}
return -1;
}

int main(int argc, char *argv[])
{
list<list<char*>*> lisRow;
list< char* > strings;
strings.push_back( "ACD" );
strings.push_back( "FDD" );
lisRow.push_back( &strings );
list< char* > strings2;
strings2.push_back( "ACDF" );
strings2.push_back( "FDDI" );
lisRow.push_back( &strings2 );
cout << CompInRows( "FDD", &lisRow ) << endl;
system("PAUSE");
return 0;
}
luohualiushui 2003-08-11
  • 打赏
  • 举报
回复
hehe
我这是偷工减料的办法
luohualiushui 2003-08-11
  • 打赏
  • 举报
回复
bool isSub(char* str,char* sub)
{
bool flag=true;
int a=strlen(str);
int b=strlen(sub);
if (a<b)
return false;
for (int i=0;i+b<a;i++)
{
for (int j=0;j<b;j++)
{
if (str[i+j]!=sub[j])
break;
}
return true;
}
return false;
}

int GetGroup(char* str)
{
if (isSub(str,"845") || isSub(str,"596") || isSub(str,"6954"))
return 1;
else if (isSub(str,"1234") || isSub(str,"567"))
return 2;
else return -1;
}

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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