2013-12-18 235 views
5

據我所知在C++字符串中有一個函數用於執行子字符串搜索:string1.find(string2)。字符數組搜索子字符串

有什麼辦法可以在char中執行相同的動作嗎?下面是我的問題:

#include <iostream> 
    #include <cstring> 
    using namespace std; 
    int main() 
    { 
     char a[]="hello world!"; 
     char b[]="el"; 
     //find substring b[] in a[] 


    } 

比方說,我需要找到字符串中的子串「厄爾尼諾」,是有可能做到這一點?

+3

'strstr',但相比只是用'的std :: string'這是相當C-等。 – chris

+1

@ godel9,這個問題是要求在char數組中找到一個子串的方法。你在那裏的鏈接只是要求一種方法來複制char數組中的某個字符串,一旦找到要複製的字符串,該字符串僅對此問題有用 – smac89

+0

@ godel9操作符要求使用C++方法查找並提取來自某個字符串的子字符串。這個標記爲重複的帖子不回答該問題。它回答了這個問題,你如何複製並且已經在C(而不是C++)中發現了一個const char字符串。我相信這個問題是堆棧溢出問題的重複,但它不是上述問題的重複。 – ltc

回答

8
char *output = NULL; 
output = strstr (a,b); 
if(output) { 
    printf("String Found"); 
} 
+0

謝謝。有用!我需要這個來做我最後一年與Linux系統相關的項目。非常感謝! – user3113716

2

這應該工作:

char a[]="hello world!"; 
char b[]="el"; 
//find substring b[] in a[] 
string str(a); 
string substr(b); 

found = str.find(substr);