Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string of type char * contains another string

I have a larger task of which contains this function. Here are the instructions;

Define a C ++ function named isPartOf , with two parameter pointers to C strings (ie of type char * , not from the not yet detailed declared C ++ data type string ) and returns a Boolean value.

In essence, the function should check whether the string pointed to it by the first parameter pointer, is part of the string pointed to it by the second parameter pointer.

Examples: isPartOf ("heart", "hypertensive heart disease") returns true back isPartOf ("screw", "Case Involving wheelchair") returns false back.

I have been learning C for a year and have only begun learning C++ and I am finding it hard to understand the use of 'char *' and parameters in general. It took me awhile to understand pointers and now parameters have thrown me off. I have tried this code with probably all possible iterations of * and & just to see if it will work but it does not.

#include <iostream>

using namespace std;

void isPartOf(char *, char *);

int main()
{
    char * Word;
    char * Sentence;

    cout << "Please enter a word: ";
    cin >> Word;
    cout << endl << "Please enter a sentence: ";
    cin >> Sentence;
    cout << endl;

    isPartOf(Word, Sentence);

    if (isPartOf(Word, Sentence))
    {
        cout << "It is part of it";
    }
    else
    {
       cout << "It is not part of it";
    }
}

void isPartOf(char a, char b)
{

}

My two main questions here are;

  1. How do parameters work in this case?
  2. Is there a function that will check if a string exists in a string? If not, how should I start going about coding a function of the sort?
like image 983
Pejman Poh Avatar asked Oct 17 '25 04:10

Pejman Poh


1 Answers

Since this is C++, the simplest solution would be to use string. You can't actually cin a character array the way you're trying to (that code doesn't do what you think it does), so that solves your input problem too:

std::string Word, Sentence;
cout << "Please enter a word: ";
std::getline(std::cin, Word);
cout << endl << "Please enter a sentence: ";
std::getline(std::cin, Sentence);
cout << endl;

if (isPartOf(Word, Sentence)) { 
    // ...
}

The other nice thing about string is that it makes isPartOf() very simple:

bool isPartOf(const std::string& word, const std::string& sentence) {
    return sentence.find(word)    // this returns the index of the first instance
                                  // word
           != std::string::npos;  // which will take this value if it's not found
}

Alternatively, it can be implemented using strstr:

    return strstr(sentence.c_str(), word.c_str());
like image 108
Barry Avatar answered Oct 18 '25 20:10

Barry