栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构、字符串、C语言】统计字符串中不同字符出现的频度

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构、字符串、C语言】统计字符串中不同字符出现的频度

【数据结构、字符串、C语言】统计字符串中不同字符出现的频度

问题描述完整代码

问题描述

写一个算法统计在输入字符串中各个不同字符出现的频度并打印(字符串中的合法字符为A-Z这26个字母和0-9这10个数字)

完整代码
#include
#define MAXLEN 255
using namespace std;
#include

struct String {
	char str;
	struct String* next;
	String() {//初始化
		str = {};
		next = NULL;
	}
};
struct SString {
	int length;
	String* head;
	String* tail;
	SString() {//初始化
		length = 0;
		head = new String;
		tail = head;
	}
};
class Printf {
public:
	void Print(String* p) {
		printf("%cn", p->str);//打印递增序列
	}
};
class Sstring :public Printf {
private:
	Printf printObj;
public:
	String* creat(SString& SS, char* ch) {
		int i = 0;
		while (i != strlen(ch)) {
			if (SS.length == 0) {
				SS.head->str = ch[i];
				SS.tail = SS.head;
			}
			else {
				SS.tail->next = new String;
				SS.tail->next->str = ch[i];
				SS.tail = SS.tail->next;
				SS.tail->next = NULL;
			}
			i++;
			SS.length++;
			//printObj.Print(SS.tail);
		}
		return SS.head;
	}
};
void Compare(SString& SS) {
	int i = 0;
	int k[MAXLEN] = { 0 };//用来保存字符频度
	int length = 0;
	char c;//c用来保存需要计算的字符
	String* p;//外循环移动
	String* q1;//用于内循环
	String* q2;//和删除字符
	p = SS.head;
	if (SS.length == 0)
		printf("字符串为空,字符频度为0!");
	while (p != NULL)
	{
		q1 = p;
		if ((q1->str >= 48 && q1->str <= 57) || (q1->str >= 65 && q1->str <= 90))//串中的合法字符才能进行频度计算
		{
			length++;//有效字符长度加1
			c = q1->str;//c来保存字符
			k[i]++;
			if (q1 == SS.head) {
				SS.head = q1->next;
				q2 = q1;
				delete q2;
				q1 = SS.head;
				p = SS.head;
			}
			else {
				q2 = q1;
				q1 = q1->next;
			}
			while (q1 != NULL) {
				if (q1->str == c) {
					k[i]++;
					//n[i] = c;
					q2 = q1;
					q1 = q1->next;
					if (q2 == SS.head) {
						p = q1;
						SS.head = q1;
					}
					delete q2;//保存字符后就删除单链表中的字符
				}
				else {
					q2 = q1;
					q1 = q1->next;
				}
			}
			i++;
		}

	}
	ofstream fout;
	fout.open("frequentness.txt", ios::app);
	cout << "各字符的频度为: n";
	for (int m = 0; m <= i; m++) {
		fout << k[m] << "n";
		cout << k[m] << "n";
	}
	fout << flush;
	fout.close();
}

int main() {
	Sstring S;
	SString SS;
	char ch[MAXLEN] ;
	gets_s(ch);
	String* head = S.creat(SS, ch);
	Compare(SS);
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/767683.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号