Home > Software design >  C , Find out if a string contains a substring?
C , Find out if a string contains a substring?

Time:09-11

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.";
  }
 }

CodePudding user response:

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.

  • Related