0
点赞
收藏
分享

微信扫一扫

C++:单词数量、长度统计

登高且赋 2022-01-22 阅读 50
c++

问题:

代码:

#include<iostream>
#include<algorithm>
using namespace std;
void split(char*str);
int main() 
{
	char str[500];
	cin.getline(str,500);
	split(str);
	return 0; 
}
//如果有最长的单词不只一个,输出最先找到的那个 
void split(char*str)
{
	//tempw为最长单词在word数组中的位置,templ为最长单词的长度 
	int tempw=0,templ=0,i=0,m=0,n=0;
	//将分割后的单词存入word数组 
	char word[500][500];
	//当该段英文没有结束时 
	while(str[i]!='\0')
	{
		//当遇到空格时,当前为一个单词 
		if(str[i]==' ')
		{
			//比较当前单词长度与templ,若当前单词长度大于templ,则将m赋值给tempw,n赋值给templ 
			if(n>templ)
			{
				tempw=m;
				templ=n;
			}
			//当前单词分割完成,分割下一个单词 
			m++; 
			n=0;
		}
		//没遇到空格时,即当前单词没有完成分割 
		else
		{
			//记录单词 
			word[m][n]=str[i];
			n++;
		}
		i++;
	} 
	cout<<"单词的数量:"<<++m<<endl;
	cout<<"最长单词的长度:"<<templ<<endl;
	cout<<"长度最长的第一个单词:";
	for(int j=0;j<templ;j++)
	{
		cout<<word[tempw][j];
	} 
}

运行结果:

 

举报

相关推荐

0 条评论