Hi all! So assuming that i'm only able to use std lib functions and strings, can anyone give any insight on how I would loop through each word of a sentence/string? I know that ideally i'd want to pull out each word and do what I need to do to it, and then continue onto the next one, to compare it to another string and see if any words match. Though i'm not sure where to proceed from here:
#include <string>
#include <cctype>
// return next word in the string after position pos
// (or an empty string if there are no more words)
// update pos to the position just after the last character in word
std::string next_word( const std::string& sentence, std::size_t& pos )
{
// skip over leading non-alpha characters
while( pos < sentence.size() && !isalpha( sentence[pos] ) ) ++pos ;
std::string word ;
// add consecutive alpha characters one by one to the word
for( ; pos < sentence.size() && isalpha( sentence[pos] ) ; ++pos ) word += sentence[pos] ;
return word ;
}
// return true if sentence contains word
// note: case sensitive, assumes word does not contain non-alpha characters
// TO DO: consider making the comparison case-insensitive
bool contains_word( const std::string& sentence, const std::string& word )
{
std::size_t pos = 0 ;
while( pos < sentence.size() )
if( next_word( sentence, pos ) == word ) returntrue ;
returnfalse ;
}
Forgive me if i'm way off somewhere, but i'm getting a function-definition error for the code thus far ( I should note that I do not need to worry about capitals or lower cases, so long as the words match):
#include <iostream>
#include <string>
#include <cctype>
// return next word in the string after position pos
// (or an empty string if there are no more words)
// update pos to the position just after the last char in word
std::string next_word( const std::string& sentence, std::size_t& pos )
{
// skip over leading non-alpha characters
while( pos < sentence.size() && !isalpha( sentence[pos] ) ) ++pos ;
std::string word ;
// add consecutive alpha characters one by one to the word
for( ; pos < sentence.size() && isalpha( sentence[pos] ) ; ++pos ) word += sentence[pos] ;
return word ;
}
// return true if sentence contains word
// note: case sensitive, assumes word does not contain non-alpha characters
// TO DO: consider making the comparision case-insensitive
bool contains_word( const std::string& sentence, const std::string& word )
{
std::size_t pos = 0 ;
while( pos < sentence.size() )
if( next_word( sentence, pos ) == word ) returntrue ;
returnfalse ;
}
int main()
{
const std::string sentence = "how now brown cow!" ;
const std::string word = "brown" ;
if( contains_word( sentence, word ) ) std::cout << "found the word in sentence\n" ;
}