您的位置:首页 > 编程语言 > C语言/C++

判断字符串匹配判断 c++

2017-10-11 15:48 246 查看
环境:

centos

c++

匹配情况分类

1 字符串完全匹配 compare

2 字符串匹配到起始位置

3 字符串匹配到末尾位置

4 字符串匹配在中间位置

5 字符串未能匹配到

code

#include <iostream>
#include <string>

int main()
{
string str = "abcdef中国汽车";
string t = "bc";
pos = str.find(t);

if(!str.compare(t))
{
std::cout << "1 str is equal to t" << std::endl;
}
else if(pos == 0)
{
std::cout << "2 t is match at the begin of str" << std::endl;
}
else if(pos + t.length() == str.length())
{
std::cout << "3 t is match at the begin of str" << std::endl;
}
else if(pos  != string::npos)
{
std::cout << "4 t is match at the middle of str" << std::endl;
}
else
{
std::cout << "5 t is not matched in str" << std::endl;
}

return 0;
}


补充说明

1 对于完全匹配

除了上面的code中实例外还可以判断条件

if(pos==0  &&  pos + t.length() == str.length() )
{
std::cout << "1 str is equal to t" << std::endl;
}


2 对于中间位置匹配

基于前面的 3 种条件过滤,4种判断条件也可以改为

if(pos > 0 && pos < str.length())
{
std::cout << "4 t is match at the middle of str" << std::endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++