title: Count unique words in a string in C++
body: <p>I want to count how many unique words are in string 's' where punctuations and newline character (<code>\n</code>) separates each word. So far I've used the logical or operator to check how many wordSeparators are in the string, and added 1 to the result to get the number of words in string s.</p>
  
  <p>My current code returns 12 as the number of word. Since 'ab', 'AB', 'aB', 'Ab' (and same for 'zzzz') are all same and not unique, how can I ignore the variants of a word? I followed the link: <a href="http://www.cplusplus.com/reference/algorithm/unique/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/algorithm/unique/</a>, but the reference counts unique item in a vector. But, I am using string and not vector.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  using namespace std;
  
  bool isWordSeparator(char &amp; c) {
  
      return c == ' ' || c == '-' || c == '\n' || c == '?' || c == '.' || c == ','
      || c == '?' || c == '!' || c == ':' || c == ';';
  }
  
  int countWords(string s) {
      int wordCount = 0;
  
      if (s.empty()) {
      return 0;
      }
  
      for (int x = 0; x &lt; s.length(); x++) {
      if (isWordSeparator(s.at(x))) {
              wordCount++;
  
      return wordCount+1;
  
  int main() {
      string s = "ab\nAb!aB?AB:ab.AB;ab\nAB\nZZZZ zzzz Zzzz\nzzzz";
      int number_of_words = countWords(s);
  
      cout &lt;&lt; "Number of Words: " &lt;&lt; number_of_words  &lt;&lt; endl;
  
      return 0;
  
  }
  </code></pre>