通过有限状态机实现指定文本的单词统计

代码实现

WordStatistic.h:

#pragma once
#include <iostream>
#include "string.h"
using namespace std;

#define OUT 0   //单词外
#define IN 1    //单词内
#define INIT OUT  //初始状态为单词外

class WordStatistic
{
public:
    //初态 字符外为0 字符内为1
    int status;
    //统计文本字数 
    void word_amount();
    //判断字符是否是标点符号
    bool is_symbol(char &c);

};

WordStatistic.cpp:

#include "WordStatistic.h"
#include "fstream"

//字符统计
void WordStatistic::word_amount(){
    //定义文件流对象
    fstream ifs;
    //当前状态
    int status = INIT;
    //读取指定文件内的字符
    ifs.open("test.txt",ios::in);
    if (!ifs.is_open())
    {
        cout<<"文件打开失败"<<endl;
    }
    else
    {
        cout<<"文件打开成功"<<endl;
        //定义变量amount初始值为0用来记录指定文件内的字符数量
        int amount = 0;
        //挨个读取字符并调用函数判断字符是否是标点符号 如果不是标点符号,字符变量++
        char c;
        while( (c = ifs.get()) != EOF)
        {
            // cout<<c<<endl;
            //遇到字符 - 状态不变
            if (c == '-')
            {
                //符号-后面紧跟换行符的话状态不变
                if((c = ifs.get()) == '\n');
                continue;
            }
            if (is_symbol(c))
            {
                status = OUT;
            }
            else if(status == OUT)
            {
                status = IN;
                amount++;
            }
        }
        ifs.close();
        cout<<"本篇文章的总字数为: "<<amount<<endl;
    }
}

//判断是否是标点
bool WordStatistic::is_symbol(char &c){
    if (c == ',' || c == '.' || c == '/' || c == '?' || c == ';' || c == '+' || c == ' ' || c == '\n')
    {
        return 1;
    }
    else 
    return 0;
}

main.cpp

#include <iostream>
#include <fstream>
#include "WordStatistic.h"
using namespace std;


int main()
{
    WordStatistic file;
    file.word_amount();
    // cout<<"hello world"<<endl;
    return 0;
}

测试文本test.txt

sdf asdfsdf asdfsdf asdf jlkj, , . / sdf-
sdf soij-sadfh -
sdfs
kkkk

测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值