Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++, Find out if a string contains a substring?

I don’t know how to use the find() function to check if a string contains a substring, then the program should print out all Words, and "Contains" if Sentence contains at least one of them. Can anyone help me out? My usage of find() sets A always to true. Thanks for help

#include <iostream>
#include <string>
using namespace std;

string Words, Sentence, buf;
int i, n, j = 0;
string arr[20];
bool A;

int main() {

cout << "Words separated by slashes";
cin >> Words;
cout << "Sentence";
cin >> Sentence;

for (i = 0; i <= Words.length(); i++)
{
if (Words[i] != '/')    
{
    buf = buf + Words[i];
}
else
{  
    arr[n] = buf;
    n = n + 1;
    buf = "";
 } 
 }
 for (j = 0; j <= n; j++)
 { 
 cout << arr[j] << "\n";

 if (Sentence.find(arr[j]) != string::npos)
 {
     A = true;
  }
 }  
 if (A == true)
 {
 cout << "Contains.";
 }
 else
 {
 enter code herecout << "Does not contain.";
  }
 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are a few bugs and issues in this code I think, but the biggest is the for loops all go too far by one.

for (i = 0; i <= Words.length(); i++)

and

for (j = 0; j <= n; j++)

should be

for (i = 0; i < Words.length(); i++)

and

for (j = 0; j < n; j++)

The valid indexes for a string, vector or array are zero upto but not including the size of the string, vector or array.

This mistake causes the bug that you see. Suppose you have two words in arr, e.g. arr = { "stack", "overflow", "", "", ... } . Because you go around the for loop one too many times you end up searching for arr[2] which equals "". This search always succeeds because every string contains the empty string. And so you always set A to true.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading