10

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
  • 123
  • 1
  • 1
  • 4
  • 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

23
char *output = NULL;
output = strstr (a,b);
if(output) {
    printf("String Found");
}
Elixir Techne
  • 1,848
  • 15
  • 20
  • Thank you. It works! I need this in doing my final year project related with Linux system. Really thanks a lot! – user3113716 Dec 18 '13 at 05:55
  • `strstr` returns a `const char*` in some implementation. – Martin Sep 03 '18 at 23:23
  • Is it really necessary to initialize `output` to `NULL` at the start? Can't you just do `char *output = strstr (a,b);`? (new to c++, but that seems fine since the description of strstr says "Returns a pointer to the first occurrence of str2 in str1, **or a null pointer if str2 is not part of str1**.") – Venryx Jul 30 '23 at 12:17
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
  • 188
  • 3
  • 13