0

I'm trying to make a program that checks if a string contains a substring of another string, but it's not working.

Here is my code:

#include <iostream>
#include <algorithm>

using namespace std;

//Struct to store information
struct strings {
    char string1[20], string2[20];
} strings;

//Function to check if the strings are equal
void equalCheck(){
    int check = 0, i = 0;
    while (strings.string1[i] != '\0' || strings.string2[i] != '\0'){
        if (strings.string1[i] != strings.string2[i]){
            check = 1;
            break;
        }
        i++;
    }
    if (check == 0){
        cout << "The strings are equal" << endl;
    }
    else
        cout << "The strings are not equal" << endl;

}

//Function to check for a substring
void substringCheck(){
    if (strings.string1.find(strings.string2) != string::npos) {
        cout << "found!" << '\n';
    }

}

int main() {


    //Ask the user for two strings
    cout << "Please type the first string: ";
    cin >> strings.string1;
    cout << "Please type the second string: ";
    cin >> strings.string2;

    //Prints out the two strings
    //cout << "The two strings are " << strings.string1 << " and " << strings.string2;

    equalCheck();
    substringCheck();

    return 0;
}

This is the problem I get:

Problem

Any ideas?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • char datatype does not have function find – Omid CompSCI Nov 06 '21 at 21:22
  • 3
    Is there a reason you are not using `std::string`? That one does have `find` method. If for some reason you insist on dealing with C-style strings, you are looking for `strstr` function. – Igor Tandetnik Nov 06 '21 at 21:23
  • Since you want to write in c++ this might answer your question. https://stackoverflow.com/questions/2340281/check-if-a-string-contains-a-string-in-c – AngelosFr Nov 06 '21 at 21:23
  • @IgorTandetnik This is the first time i code in c++ :P so I dont really know what I'm doing –  Nov 06 '21 at 21:26
  • @AngelosFr Yeah thats the post i tried to follow, but i couldnt get it to work and i dont know why :( –  Nov 06 '21 at 21:27

1 Answers1

2

Wouldn't it be easier for strings to have two std::string instead of two char[20]?

Then you would be able to say this with no problem:

if (strings.string1.find(strings.string2) != std::string::npos) {
    std::cout << "found!\n";
}

char is not a class like std::string, it doesn't have any member functions. This means char[20].find doesn't exist. std::string is a class, however. And it does have a member function called std::string::find(), so doing this to a std::string is legal.

coulomb
  • 698
  • 6
  • 16
  • Yeah that worked, thanks! I did not know you could use ```std::string``` instead of char. First time in C++ and I'm used to ```char``` from C –  Nov 06 '21 at 21:30