上机题:
模拟词法分析的过程,编写一个程序,用于统计文件中单词的总数,不同单词的数目。(假设输入文件中只包含字母和空格)
eg: I love Dalian and I love DLUT
单词总数:7
不同单词数目:5
#include <stdio.h>
#include <iostream>
#include <string.h>
int main()
{
using namespace std;
string sentence;//输入的字符串
cout << "Please input the sentence:";
getline(cin,sentence);
int countlen = sentence.length();//字符串的长度
int countchar = 1;//统计有多少个空格,+1即单词数量
for (int i = 1; i <= countlen; i++) {
if (sentence[i] == ' ' && sentence[i - 1] != ' ') {
countchar++;
}
}
cout << "单词总数:" << countchar<<endl;
char sentencechar[20][20];//句子拆成单词
int i = 0;//句子长度下标
int j = 0;//单词下标
int k = 0;//单词中字母下标
while ( i <= countlen-1) {
if (sentence[i] != ' ') {
sentencechar[j][k] = sentence[i];
k++;
i++;
}
else if(sentence[i] == ' ') {
sentencechar[j][k] = '\0';
k = 0;
j++;
i++;
}
}
int countcom[20] = {0};//统计相同单词数量
int com = 0;
//检查相同单词
for (int m = 0; m <= j-1; m++) {
for (int n = m + 1; n <= j; n++) {
if (strcmp(sentencechar[m], sentencechar[n]) == 0) {
countcom[com]++;
com++;
}
}
}
int countdiffer = countchar;//不同单词=总词数-相同单词出现次数+1
for (int m = 0; m < com; m++) {
countdiffer = countdiffer - countcom[m];
}
cout << "不同单词数目:" << countdiffer;
return 0;
}