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

环境:
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种判断条件也可以改为

ifpos > 0 && pos < str.length())
{
    std::cout << "4 t is match at the middle of str" << std::endl;
}

猜你喜欢

转载自blog.csdn.net/a1368783069/article/details/78204549