How to count words in a string with punctuation in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_WORDS 128
#define MAX_LEN 32

// Function to strip punctuation from both ends of a word
void strip_punctuation(char* word) {
    int start = 0;
    int end = strlen(word) - 1;

    // Trim leading punctuation
    while (start <= end && ispunct((unsigned char)word[start])) {
        start++;
    }

    // Trim trailing punctuation
    while (end >= start && ispunct((unsigned char)word[end])) {
        end--;
    }

    // Shift the cleaned word to the beginning of the buffer
    int i, j = 0;
    for (i = start; i <= end; i++) {
        word[j++] = word[i];
    }
    word[j] = '\0';
}

// Function to check if a word is alphabetic
int is_alpha_word(const char* word) {
    if (strlen(word) == 0) return 0;
    
    for (int i = 0; word[i]; i++) {
        if (!isalpha((unsigned char)word[i])) return 0;
    }
    
    return 1;
}

int main() {
    const char* s = "python! ,,c, c++. c# $$$java@# php.";
    char buffer[256];
    
    strncpy(buffer, s, sizeof(buffer));
    buffer[sizeof(buffer) - 1] = '\0';

    int count = 0;
    char* token = strtok(buffer, " ");
    while (token != NULL) {
        strip_punctuation(token);
        if (is_alpha_word(token)) {
            count++;
        }
        token = strtok(NULL, " ");
    }

    printf("%d\n", count);
    
    return 0;
}


    
/*
run:

6

*/

 



answered Nov 2, 2025 by avibootz
...