Question:
Finding a char array in another char array using C++?
anonymous
2013-01-30 08:42:28 UTC
I have made the following program to find a char array in another char array.

void main()
{
char sentence_from_user[10];
char search_data[10];

cin>>sentence_from_user;
cin>>search_data;


int total_founds=0;

//finding whether the data is present in the sentence.
int i=0;
int j=0;

for (; i {
if (sentence_from_user[i]==search_data[j])
{total_founds++;
j++;
}

if (total_founds==strlen(search_data)) { cout<<"The data found at index "<
else if (sentence_from_user[i]!=search_data[j])
{ total_founds=0;
j=0;

}
}



}


for example;
char arr1[10]="123welcome";
char arr2[10]="welcome";

the program must return the index number 3 of arr1, as arr2 is present from there. However the program is not working. If you have some other logic, you may also share that.
Three answers:
?
2013-01-30 11:59:06 UTC
Just use C++'s string find - here's an example -

http://www.cplusplus.com/reference/string/string/find/
?
2016-10-13 09:29:43 UTC
you're getting perplexed between C strings (char *, char[]) and C++ string gadgets (string). you may no longer use C string applications right now on C++ strings and vice versa. you may although get on the underlying C string in a C++ string utilising the c_str() approach, e.g. string s = "hi"; int len = strlen(s.c_str());
Cubbi
2013-01-30 20:10:33 UTC
If you must use null-terminated character sequences stored in char arrays (which is a silly thing to do, of course), the function to search for one such sequence inside another is called strstr().

Related functions: search() searches for an array inside another array (but it is hard to use with null-terminated sequences that you're dealing with), and the already-mentioned string::find() searches for a string inside another string.



Here are all three in action with your example:



#include

#include

#include

#include



int main()

{

     char arr1[] = "123welcome";

     char arr2[] = "welcome";



     // using strstr()

     char* p1 = std::strstr(arr1, arr2);

     if(p1)

          std::cout << "Match at position " << p1 - arr1 << '\n';

     else

          std::cout << "No match\n";



     // using search()

     char* end1 = arr1 + std::strlen(arr1);

     char* end2 = arr2 + std::strlen(arr2);

     char* p2 = std::search(arr1, end1, arr2, end2);

     if(p2 != end1)

          std::cout << "Match at position " << p2 - arr1 << '\n';

     else

          std::cout << "No match\n";



     // using string::find

     std::string s1(arr1);

     std::string s2(arr2);

     std::size_t pos = s1.find(s2);

     if(pos != std::string::npos)

          std::cout << "Match at position " << pos << '\n';

     else

          std::cout << "No match\n";

}



online demo: http://ideone.com/lWhQ8S


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...