2013-12-18 174 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);