Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to count words in a string with punctuation in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <string>
#include <cctype>
#include <algorithm> // all_of

bool isAlphaWord(const std::string& word) {
    // Strip leading and trailing punctuation
    size_t start = 0;
    while (start < word.size() && ispunct(word[start])) start++;

    size_t end = word.size();
    while (end > start && ispunct(word[end - 1])) end--;

    std::string stripped = word.substr(start, end - start);

    // Check if the stripped word is alphabetic
    return !stripped.empty() &&
           std::all_of(stripped.begin(), stripped.end(), [](char ch) {
               return std::isalpha(static_cast<unsigned char>(ch));
           });
}

int main() {
    std::string s = "python! ,,c, c++. c# $$$java@# php.";
    std::istringstream iss(s);
    std::string word;
    int count = 0;

    while (iss >> word) {
        if (isAlphaWord(word)) {
            count++;
        }
    }

    std::cout << count << std::endl;
}

  
/*
run:
  
6
  
*/

 



answered Nov 2, 2025 by avibootz
...