Recognise a word inside a string

Pages: 12
What do I have to do so that you can enter a whole sentence and that the program recognizes a certain word inside the code? If I, for example, enter the sentence: "I hope it won't rain today" (using getline(cin, string*)), how do I write: if the string contains the word rain,...?
1
2
3
4
5
6
7
std::istringstream is( "I hope it won't rain today" );

auto x = std::find( std::istream_iterator<std::string>( is ),
	            std::istream_iterator<std::string>(),
		    "rain" );

if ( x != std::istream_iterator<std::string>() ) std::cout << *x << std::endl;
}
Last edited on
I tried to copy your code and run it, but it didnt work. There were alot of error messages. For example missing initialisers or unrecognized istream_iterator. So it didnt work. Could you or someone else check whats wrong?

PS. Does it matter that I use windows?
Depends on what you mean by a word.

1
2
3
4
5
6
const std::string str = "Hopefully it won't rain today; I don't want to get wet." ;

// is the word 'hopefully' present in the string?
// is the word 'hope' present in the string?
// are the words 'today' and 'wet' present in the string?
// is 'today;' a word? 



> Does it matter that I use windows?

No, it doesn't.

1
2
3
4
#include <string>
#include <sstream>
#include <iterator>
#include <algorithm> 
The string class has a find method that does a linear search and returns where it found a match. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
#include <iostream>

int main()
{
	const std::string sentence = "My printer is not working.";
	std::cout << "sentence: " << sentence << std::endl;

	std::string search;
	size_t pos;

	search = "printer";
	pos = sentence.find(search);
	if (pos != std::string::npos)
		std::cout << "sentence contains " << search << std::endl;
	else
		std::cout << "sentence does not contains " << search << std::endl;

	search = "scanner";
	pos = sentence.find(search);
	if (pos != std::string::npos)
		std::cout << "sentence contains " << search << std::endl;
	else
		std::cout << "sentence does not contains " << search << std::endl;

	return 0;
}
output:
1
2
3
sentence: My printer is not working.
sentence contains printer
sentence does not contains scanner

@xantavis


You have to include the following headers

1
2
3
4
5
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <string> 
He'll also need a C++11 compiler for your code.
@kbw
He'll also need a C++11 compiler for your code.


Only if he will use the type specifier auto. However it is simple to substitute it for

std::istream_iterator<std::string> x
Last edited on
@kbw:
Your code worked, thx!

@vlad
Your code works now too, thx again!



Now I`ve only got to choose which which of these two ways I`ll choose...
Why not write a function that finds words?

Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cctype>
#include <iostream>
#include <string>

bool contains_word(const std::string& sentence, const std::string& word)
{
        size_t pos = 0;
        // Find the start of 'word' in 'sentence'.
        while ((pos = sentence.substr(pos).find(word)) != std::string::npos) {
                // Make sure it's actually a word (e.g. "rain" could be part of "drain").
                // isalpha checks if the given character is in the alphabet. Here we check
                // if the characters before and after 'word' are alphabet characters. If neither
                // of them is an alphabet character then we've found a whole word.
                if (!(isalpha(sentence[pos - 1])) || !(isalpha(sentence[pos + word.size() + 1])))
                        return true;
        }
        // If we get to here then we didn't find any instance of 'word' that was a whole word.
        return false;
}

The other methods of finding 'word' in 'sentence' don't take into account that the word could be part of another word (like 'rain' in 'drain'), in which case it wouldn't really be a word at all.

Now you can just do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
        std::string sentence, word;
        // Get the sentence to search.
        std::cout << "Sentence: " << std::flush;
        std::getline(std::cin, sentence);
        // Get the word to search for.
        std::cout << "Word: " << std::flush;
        std::getline(std::cin, word);
        // Say whether the sentence contains the word.
        if (contains_word(sentence, word))
                std::cout << "The sentence contains the word." << std::endl;
        else
                std::cout << "The sentence does not contain the word." << std::endl
        return 0;
}


Lastly, you might want to change "const std::string&" to just "std::string" if you haven't learned about references yet.
You are right chrisname! That is what Ill do. But first, there is a small problem:

I am doing all this inside a class and not inside the main.cpp . I placed the bool into my main void-function and ran the program, but there were these errors:
expected } at end of input
(There is definitely no } missing!)
a function definition is not allowed here before { token


My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "Talk.h"
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <ctime>
using namespace std;

Talk::Talk(){}


void Talk::Voidex () {

    bool Search(string sentence, string word){
        size_t pos = 0;
        while ((pos = sentence.substr(pos).find(word)) != string::npos)
        {
                if (!(isalpha(sentence[pos - 1])) || !(isalpha(sentence[pos + word.size() + 1])))
                        return true;
        }
        return false;}



    string x;

    getline (cin, x);

int wert = 0;

        if (Search(x,"less")) wert = 1;
        else if (Search(x,"more")) wert = 3;

cout << wert;
}



Last edited on
Let me see Talk.h.
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef TALK_H
#define TALK_H


class Talk
{
    public:
        Talk();
        void Voidex ();
};

#endif 

Wait, why have you put a function inside a function? This isn't Javascript, you can't do that in C++.
u can do that in javascript!?!?!? does the function gain scope
Yeah, it's one way to fake classes (since Javascript lacks them as it has a different way of implementing OOP, but sometimes you might want to use classes anyway). You can do something like this:
1
2
3
4
5
6
7
function Square(width, height) {
        this.width = width;
        this.height = height;
        this.getArea = function() {
                return this.width * this.height;
        };
}

and then you can make objects like this:
1
2
var square = new Square(2, 2);
alert('2x2 = ' + square.getArea());

Just like in any other language.
Last edited on
so since the problem was solved i am going to hijack the thread for a little bit to ask some javascript questions. i just got into javascript yesterday but ive got the basics. question one what is "this" question two: is javascript for the most part a collection of objects?
'this' in Javascript is similar to 'this' in C++, except it's a reference instead of a pointer. When an object uses 'this' in many OOP languages (Python uses 'self' instead but it's otherwise the same) it simply refers to that object. For example, in C++:
1
2
3
4
5
6
7
8
9
10
class Object {
public:
        Object* GetThis()
        {
                return this;
        }
};
// ...
Object object;
Object* pObject = object.GetThis();

pObject now points to object.
Last edited on
If I put the bool outside the void, then other error messages appear...
What error messages? Post them here. You just can't put a function inside another function in C++, unless it's a lambda function.
Pages: 12