36_单词分析

本文展示了四种C++代码实现,用于统计用户输入字符串中出现次数最多的字符,包括使用数组、字符数组以及遍历ASCII码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单词分析

在这里插入图片描述

实现1

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>

int main()
{
	int a[128] = { 0 };  //存字符出现的次数,你想一想,合理字符就128个。明显的


	char s[1000]; 
	scanf("%s", s); 
	int len = strlen(s);

	int max = 0; //存出现次数最多次的字符 和次数
	char t = 0; 

	//一个冒泡搞定
	for (int i = 0; i < len; i++)
	{
		a[s[i]]++;
		if (max < a[s[i]]) //先比次数,次数相同再比ASCII
		{
			max = a[s[i]]; 
			t = s[i];
		}
		else if (max == a[s[i]])
		{
			if (t > s[i])
			{
				t = s[i];
			}
		}
	}
	printf("%c\n%d", t, max);
	
}

实现2

#include<iostream>
#include<string>




int main()
{
	std::string str;
	std::cin >> str;
	int n = str.size();

	int s[1010];
	//存字符出现的次数
	for (int i = 0; i < n; i++)
	{
		int a = str[i] - 'a';
		s[a]++;
	}

	//走一个冒泡
	int max = 0; char ch;
	for (int i = 0; i < 100; i++)
	{
		if (max <= s[i])
		{
			if (max < s[i])
			{
				max = s[i];
				ch = (char)(i + 'a');
			}
			else if (max == s[i])
			{
				max = s[i];
				ch = ch;
			}

		}
	}

	std::cout << ch << std::endl;
	std::cout << max << std::endl;
	return 0;
}


实现3

#include<iostream>
#include<string>

using namespace std;
char m[1005]; 
int n[1005]; 
char c;
bool b[1005]; 
string str;

int main()
{
	int max = 0; 
	cin >> str;
	memset(b, false,sizeof(b));
	for (int i = 0; i < str.size(); i++)
	{
		while (b[i])
		{
			i++;
		}
		m[i] = str[i];
		b[i] = true;
		n[i] = 1;

		//对于字符item来说,总是拿他和他后面的字符对比
		for (int j = i + 1; j < str.size(); j++)
		{
			if (m[i] == str[j])
			{
				n[i]++; 
				b[j] = true; //找到相同的,就给标识为true 次数也加1
			}
		}

		//比一次当前最大值,有变动更新一波
		if (max <= n[i])
		{
			if (max == n[i])
			{
				if ((c - 'a') <= (m[i] - 'a'))
				{
					c = c;
				}
				else
				{
					c = m[i];
				}
			}
			else
			{
				max = n[i];
				c = m[i];
			}

		}
	
	}
	cout << c << endl; cout << max << endl;
	return 0;
}

实现4

#include<iostream>
#include<string>
using namespace std;
int main() 
{
	char a[1005];
	int len;
	scanf("%s", a);
	len = strlen(a);

	int b[26] = { 0 };

	//初始化b数组,存用户注入字符串 每一个(字符+'a')对应的ASCII码(数字)出现次数
	for (int i = 0; i < len; i++)
	{
		b[a[i] - 'a']++;
	}

	//遍历次数数组,b数组元素经过约束本身已经有序
	int max1 = 0, j;
	for (int i = 0; i < 26; i++)
	{
		if (max1 < b[i])
		{
			max1 = b[i];
			j = i; 	//下标就是目标字符距离'a'字符的偏移咯
		}
	}

	std::cout << char('a' + j) << std::endl << max1;
	return 0;
}

	
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值