C/C++判断字符串是否包含某个子字符串


C风格

#include <iostream>
#include <string>
#include <cstring>
using  namespace  std;
int  main()
{
     string a= "abcdefghigklmn" ;
     char  *b= "def" ;
     char  *c= "123" ;
     
     if ( strstr (a.c_str(), b) == NULL) //在a中查找b,如果不存在,
         cout <<  "not found\n" ; //输出结果。
     else //否则存在。
         cout << "found\n" //输出结果。
     if ( strstr (a.c_str(), c) == NULL) //在a中查找b,如果不存在,
         cout <<  "not found\n" ; //输出结果。
     else //否则存在。
         cout << "found\n" //输出结果。
     return  0;
}
 
C++风格
#include <iostream>
#include <string>
using  namespace  std;
int  main()
{
     string a= "abcdefghigklmn" ;
     string b= "def" ;
     string c= "123" ;
     string::size_type idx;
     
     idx=a.find(b); //在a中查找b.
     if (idx == string::npos ) //不存在。
         cout <<  "not found\n" ;
     else //存在。
         cout << "found\n"
     idx=a.find(c); //在a中查找c。
     if (idx == string::npos ) //不存在。
         cout <<  "not found\n" ;
     else //存在。
         cout << "found\n"
     return  0;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM