字符统计

题目描述
给出一段字符,请统计这段字符有几行,几个单词和几个字符。

定义单词为用空格或者换行符隔开的连续字符

字符定义为包括一般可见字符以及空格

输入描述:
第一行一个正整数T ,代表测试数据的组数

第二行开始为第一组测试数据,测试数据每行不超过1024个字符

每两组测试数据之间用连续的 5 个= 分隔,保证测试数据中不会出现连续的 5 个 =

输出描述:
每组测试数据在一行中输出由空格分隔的3个整数,分别代表行数,单词数和字符数
输入

2
This is a sample input.
 Hello World!!
=====
The speech by Hunyak, translated, is:
"What am I doing here?
They say, the famous Hungarian police,
that I held down my husband and chopped off his head.

But I didn't do it, I am not guilty.
I can't believe that Uncle Sam says I did it.
They say I didit, but really I didn't."

输出

2 7 37
8 55 270

说明
对于第一个样例,有2行7个单词是显而易见的
有28个字母,3个标点符号以及6个空格,所以共有37个字符
请注意换行符不算在字符个数里

在写这个题目之前,我先来简单介绍一下stringstream的用法吧,stringstream能从从从输入的getline字符串中截取一段一段的单词或者整数。
比如

#include<bits/stdc++.h>
using namespace std;
int main(){
	string s = "Hello world";
	stringstream ss(s);//将字符串s复制到ss中去
	string a;
	while(ss >> a){
		cout << a << endl;
	}
	cout << endl;
	string str = "aaa bbb 167 ccc";
	stringstream cs(str);
	string x,y,z;
	int b;
	cs >> x >> y >> b >> z;
	cout << x << endl << y << endl  << b <<endl << z;
	
	return 0;
}

运行结果
在这里插入图片描述

简单知道了stringstream的用法之后我们这道题就好解了,通过的代码如下

#include<bits/stdc++.h>
using namespace std;
int flag = 1;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int t;
	cin >> t;
	//getchar();
	while(t--){
		string s;
		int sum = 0,words = 0,Char = 0;
		while(getline(cin,s)){
		    if(s == "=====")break;
			sum ++;
			int len = s.length();
			Char += len;
			stringstream ss(s);
			while(ss >> s){
				words++;
			}
		}
		if(flag==1){
			cout<<sum-1<<" "<<words<<" "<<Char<<"\n";
			flag++;
		}
		else if(flag > 1)cout<<sum<<" "<<words<<" "<<Char<<"\n";
	}
	
	return 0;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值