I am writing a program which takes as input, a sentence (string), and my program performs various checks on that sentence.
The following is a list of simplified version of the checks:
1. Count the number of words and output it.
2. Check if the first word is HAHA.
3. Check if any word in the sentence contains the letter D. If so, output that word.
I was thinking about using the C++ string operators such as find to do this. But, I simply can't think of a way to do it with those operations.
I'm used to solving such problems using Perl. So I was thinking about using a C++ regular expression library to do this. Would using regular expression library be an overkill? Also, which C++ regexp library do you recommend? (has to be one of the standard C++ library.) Preferably, I'd like to see a good guide about the library which you suggest.
but it's not yet fully implemented by some compilers (most notably, GCC does not implement it, and does not throw errors or warnings if you try to use it)
The most portable choice today is boost.regex (which is almost exactly the same as the C++ regex)
However, the checks you listed don't require regular expressions: they are trivailly solvable with the more common string and stringbuffer operations, for example:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>
usingnamespace std;
int main()
{
string input = "HAHA, only kidDing";
istringstream buf(input); // convert to buffer
istream_iterator<string> beg(buf), end;
vector<string> v(beg, end); // parse into words
std::cout << "The number of words is " << v.size() << '\n';
if(!v.empty() && v[0] == "HAHA")
std::cout << "The first word is 'HAHA'\n";
std::cout << "The following words contain the letter 'D': ";
copy_if(v.begin(), v.end(), ostream_iterator<string>(cout),
[](const string& s){ return s.find('D') != string::npos; });
std::cout << '\n';
}