实现指定单词在文中出现次数

本文介绍了如何使用C++编写一个程序,统计指定文件中特定单词的出现次数,同时处理字符串中的标点符号。程序通过宏定义、函数实现和命令行参数传递,参考了《零声教育》的Linux服务期高级架构系统教程。
摘要由CSDN通过智能技术生成

宏定义

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//限定单词长度
#define MAX_WORD_LENGTH 100
函数

通过ispunct检查所传的字符是否是标点符号字符,为真则替换成结束符。

// 移除字符串末尾的标点符号
void remove_punctuation(char *word) {
    int len = strlen(word);
    while (len > 0 && ispunct((unsigned char)word[len - 1])) {
        word[len - 1] = '\0'; // 替换为字符串结束符
        len--;
    }
}

%99s格式化,防止缓冲区溢出;strcmp判断所指向的字符字符串是否相等,返回0则次数自增;

int count_specific_word(const char *filename, const char *word) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("打开文件错误");
        return -1;
    }

    char current_word[MAX_WORD_LENGTH];
    int count = 0;

    // 使用 %99s 确保不会超出 current_word 数组的边界
    while (fscanf(file, "%99s", current_word) == 1) {
        remove_punctuation(current_word); // 移除单词末尾的标点符号
        if (strcmp(current_word, word) == 0) {
            ++count;
        }
    }

    fclose(file);
    return count;
}
主函数

检查命令行数,防止程序没有接收到足够的参数就被调用;通过函数调用打印出次数。

int main(int argc, char *argv[]) {
    if (argc < 3) {
        fprintf(stderr, "用法: %s <文件名> <单词>\n", argv[0]);
        return -1;
    }

    const char *filename = argv[1];
    const char *word = argv[2];

    int word_count = count_specific_word(filename, word);

    if (word_count >= 0) {
        printf(" '%s' 单词出现%d 次在 %s.里\n", word, word_count, filename);
    } else {
        fprintf(stderr, "计算出错.\n");
    }

    return 0;
}
执行结果

文章参考与<零声教育>的C/C++linux服务期高级架构系统教程学习:   https://it.0voice.com/p/t_pc/course_pc_detail/camp_pro/course_2U9D57IzMfQsoiaMuokdvXYV11c

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值