概述
字符串是C++的一种重要数据类型,本次实验我们除了掌握串类型的实现方法及文本模式匹配方法,还要求计算一个文本中关键词的出现个数;在这里我简单介绍一下串的设计,及如何统计一个文本中出现的关键词。
算法思路
本次实验我采用数组的方式来做string类,当然也可以采用字符指针来做,但指针做法较为繁琐就不逐一展开介绍了,这里仅介绍字符数组做法,但文末也会附上字符指针做法的代码,如果你有兴趣也可以看看。
String类的设计思路
String()
@description: 初始化函数,简单将size置为0
void append(char str)
- @description: 连接函数
- 意在字符串尾连接一个字符
- @param {*char str}
void display()
- @description: 输出函数
- 顺序遍历字符数组,并输出该字符串
bool operator(const String &str)==
- @description: 重载 “==”
- 判断两字符串是否相同。首先对其长度进行判断
- 若长度不一则返回false;否则顺序遍历字符串
- 逐一判断对应位置是否相等,若存在一个或一个
- 以上的位置的字符不相等,则返回false,否则
- @param {*const String &str}
bool empty()
- @description: 判断字符串是否为空
- 借助记录其长度的size来判断,若size为,则
- 字符串为空,否则不为空
int length()
- @description: 返回记录字符串长度的size的值
- @return {*size}
void clear()
- @description: 清空字符串
- 直接令记录字符串长度的size为0。
void pre(const char s[], int len)
- @description: 预处理函数
- 读入预处理的关键词字符串及其长度
- @param {*const char s[], int len}
统计关键词部分算法设计
在main函数中主要采用ifstream去打开待处理文档,逐个字符读取,若为字母则将其添加到string的对象word中(这边由于计算的是一段源程序中的关键词个数,只判断小写字母),否则对该单词进行判断,判断后将word清空。
这其中需要的几个辅助函数如以下
bool is_low_letter(char c)
- @description: 判断是否为小写字母
- 值得注意的是C语言的32个关键词中均为小写
- @param {*char c}
void pretreatment()
- @description: 预处理关键词函数
- 将需要进行判断的关键词写入,该部分
- 也可改为在线输入
void calculate(const String &word, int posi)
- @description: 计算关键词是否出现
- 根据预处理的关键词个数,顺序遍历关键词,若与
- 其中之一相同,则对该关键词的计数器进行自增
- @param {*const String &word, int posi}
void out()
- @description: 输出函数
- 根据预处理的关键词个数,顺序遍历关键词,输出关键词
- 并把其出现次数,出现的位置输出
代码部分
数组实现
/*
* @Author: csc
* @Date: 2020-11-14 10:43:06
* @LastEditTime: 2020-11-20 13:24:18
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \code\data structure\str_.cpp
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#define FAST \
ios::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define pr printf
#define sc scanf
#define sf(n) scanf("%d", &n)
#define sff(n1, n2) scanf("%d %d", &n1, &n2)
#define sfff(n1, n2, n3) scanf("%d %d %d", &n1, &n2, &n3)
#define sl(n) scanf("%lld", &n)
#define sll(n1, n2) scanf("%lld %lld", &n1, &n2)
#define slll(n1, n2, n3) scanf("%lld %lld %lld", &n1, &n2, &n3)
const int N = 1e4 + 100;
const int MOD = 1e9 + 7;
#define INF 1000000
typedef long long int ll;
using namespace std;
class String
{
public:
String()
/**
* @description: 初始化函数
*/
{
size = 0;
}
void append(char str)
/**
* @description: 连接函数
* 意在字符串尾连接一个字符
* @param {*char str}
*/
{
_str[size] = str;
size += 1;
}
void display()
/**
* @description: 输出函数
* 顺序遍历字符数组,并输出该字符串
*/
{
for (int i = 0; i < size; ++i)
pr("%c", _str[i]);
}
bool operator==(const String &str)
/**
* @description: 重载==
* 判断两字符串是否相同。首先对其长度进行判断
* 若长度不一则返回false;否则顺序遍历字符串
* 逐一判断对应位置是否相等,若存在一个或一个
* 以上的位置的字符不相等,则返回false,否则
* 返回true。此处也可采用BF做。
* @param {*const String &str}
*/
{
if (size != str.size)
return false;
else
{
for (int i = 0; i < size; ++i)
if (_str[i] != str._str[i])
return false;
return true;
} //
}
bool empty(