C/C++編程判斷String字符串是否包含某個字符串實現(xiàn)示例
一、C語言風格
在C語言中,字符串存儲為字符數(shù)組,以'\0'結束。
在C的接口中,有strstr函數(shù),可以在字符串中查找另一個字符串。
char * strstr(const char *str1, const char *str2);
功能為在str1中查找str2,如果存在,那么返回查找到的起始指針,否則返回NULL。
參考代碼:
#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++風格
C++的string類提供了字符串中查找另一個字符串的函數(shù)find。
其重載形式為:
string::size_type string::find(string &);
功能為在string對象中,查找參數(shù)string類型的字符串是否存在,如果存在,返回起始位置。
不存在則返回 string::npos。
參考代碼如下:
#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; }
兩種方法在實際編程中都可以使用,效率幾乎相同。
不過相對來說使用C++的string效率更高一些,代碼也更簡便。
以上就是C++編程判斷String字符串是否包含某個字符串實現(xiàn)示例的詳細內容,更多關于C++判斷String字符串是否包含某個字符串的資料請關注腳本之家其它相關文章!
相關文章
QT線程池的使用(QThreadPool類和QRunnable類)
本文主要介紹了QT線程池的使用(QThreadPool類和QRunnable類),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-04-04Win10中VC2013安裝Unit test組件出現(xiàn)問題解決方案
本文給大家分享的是個人在Win10中VC2013安裝Unit test組件出現(xiàn)問題并最終找到解決辦法的過程,有需要的小伙伴可以參考下2016-03-03C++ 創(chuàng)建桌面快捷方式 開始菜單的實現(xiàn)代碼
這篇文章介紹了C++ 創(chuàng)建桌面快捷方式,開始菜單的實現(xiàn)代碼,需要的朋友可以參考一下2013-06-06C語言中經socket接收數(shù)據(jù)的相關函數(shù)詳解
這篇文章主要介紹了C語言中經socket接收數(shù)據(jù)的相關函數(shù)詳解,分別為recv()函數(shù)和recvfrom()函數(shù)以及recvmsg()函數(shù)的使用,需要的朋友可以參考下2015-09-09