字串操作系列_3字串中是否存在指定子串

來源:互聯網
上載者:User

       字串操作在各大小公司的筆試和面試中經常出現,“字串操作系列”的目標是整理出常見的字串操作題目,並給出筆者的參考代碼。筆者將不斷更新該系列博文,敬請關注!

題目:判斷字串中是否存在指定子串,如果存在,則返回子串第一次出現的位置,如果不存在,則返回-1,例如字串為“abcdefghijk”,當子串為“ghi”時,則返回6,當子串為“bdf”時,返回-1.

下面給出c/c++語言代碼:

#include <iostream>#include<assert.h>using namespace std;int findSubStr(char* str,char* sub){assert(str!=NULL && sub!=NULL);char* pstr = str;char* psub = NULL;int len = strlen(sub);while(*pstr != NULL){psub = sub;if(*pstr==*sub){while(*psub==*pstr && *psub!=NULL){pstr++;psub++;}//如果比較*psub == NULL,說明子串存在,返回索引if(NULL == *psub){return (pstr-str-len);}}else{pstr++;}}//子串不存在則返回-1return -1;}int main(){char str[] = "abcdefghijk";char sub[] = "ghi";cout<<findSubStr(str,sub)<<endl;return 0;}

運行結果如下:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.