7

As I know there is a function in C++ string which performs substring search: string1.find(string2).

Is there any way to perform the same action in char? Below is my question:

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


    }

let's say i need to find substring "el" in the string, is it possible to do that?

user3113716
  • 93
  • 1
  • 1
  • 3
  • 3
    `strstr`, but it's rather C-like compared to just using `std::string`. – chris Dec 18 '13 at 04:03
  • 1
    @godel9, this question is asking of a way to find a substring in char array. The link you have there is just asking for a way to copy a certain string from a char array which is only useful for this question once the string to be copied is found – smac89 Dec 18 '13 at 05:48
  • @godel9 the op is asking for the C++ way to find and extract a substring from from some string. The post this is marked as a duplicate of does not answer that question. It answers the question how do you copy and already found substring out of a const char in C (not C++). I am sure this question is a duplicate of some question on stack overflow, but it is not a duplicate of question above. – ltc Jan 13 '17 at 21:41

2 Answers2

17
char *output = NULL;
output = strstr (a,b);
if(output) {
    printf("String Found");
}
Elixir Techne
  • 1,790
  • 14
  • 19
4

This should work:

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

found = str.find(substr);
Rohit Jose
  • 168
  • 2
  • 13