3-10 串的模式匹配 (20分)

本文介绍如何使用strstr函数在C/C++中查找子字符串,并提供了一个示例程序,该程序读取主字符串和要搜索的多个子字符串,如果找到匹配项则输出匹配的位置。

用 char *strstr() 函数 ,std::c_str()函数

strstr, wcsstr, _mbsstr

Find a substring.

char *strstr( const char *string, const char *strCharSet );

wchar_t *wcsstr( const wchar_t *string, const wchar_t *strCharSet );

unsigned char *_mbsstr( const unsigned char *string, const unsigned char *strCharSet );

RoutineRequired HeaderCompatibility
strstr<string.h>ANSI, Win 95, Win NT
wcsstr<string.h> or <wchar.h>ANSI, Win 95, Win NT
_mbsstr<mbstring.h>Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIBSingle thread static library, retail version
LIBCMT.LIBMultithread static library, retail version
MSVCRT.LIBImport library for MSVCRT.DLL, retail version

Return Value

Each of these functions returns a pointer to the first occurrence of strCharSet in string, or NULL if strCharSet does not appear in string. If strCharSet points to a string of zero length, the function returns string.

Parameters

string

Null-terminated string to search

strCharSet

Null-terminated string to search for

Remarks

The strstr function returns a pointer to the first occurrence of strCharSet in string. The search does not include terminating null characters. wcsstr and _mbsstr are wide-character and multibyte-character versions of strstr. The arguments and return value of wcsstr are wide-character strings; those of _mbsstr are multibyte-character strings. These three functions behave identically otherwise.

basic_string::c_str

const E *c_str() const;

The member function returns a pointer to a nonmodifiable C string constructed by adding a terminating null element (E(0)) to the controlled sequence. Calling any non-const member function for *this can invalidate the pointer.

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    string p,s;
    cin>>s;
    int n;
    cin>>n;
    const char *temp;
    for(int i=0;i<n;i++)
    {
        cin>>p;
        temp=strstr( s.c_str(),p.c_str() );
        if( temp )
        cout<<temp<<endl;
        else
        cout<<"Not Found"<<endl;
    }
    return 0;
}


#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    string p,s;
    cin>>s;
    int n;
    cin>>n;
    const char *temp;
    for(int i=0;i<n;i++)
    {
        cin>>p;
        temp=strstr( s.c_str(),p.c_str() );
        if( temp )
        cout<<temp<<endl;
        else
        cout<<"Not Found"<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值