空格大师(space)

大家好,第二次创作,欢迎高手指导,谢谢!

不定时更新,题目+解析+评测结果+完整程序,有问题有瑕疵欢迎评论区留言!



1.题目

 

58. K12317 空格大师(space)

题目描述

科丁博士写文章的时候非常喜欢加空格,人送外号“空格大师”,小科今天闲着无事,就想统计一下科丁博士的文章中到底有多少空格,他从科丁博士的文章中,随机的挑选了一行,请你帮他统计一下这一行中有多少个空格。

输入格式

一行:一个字符串S

输出格式

输出:字符串S中空格的数量。

输入输出样例

输入样例1:复制
hello   world
输出样例1:复制
3

说明:

【样例说明】

样例1:hello和world之间有3个空格。

【数据范围】

字符串S最多包含100个字符。

【耗时限制】1000ms 【内存限制】128MB


 2.解析

题目说了这么一大串,其实就是让我们统计一行包含空格的字符串(或字符数组)。

而想要解决这道题目,我们要先搞懂怎样读空格。

下面,我们将从字符串和字符数组两方面讲解:


知识点1:读空格

1.字符串读:

getline(cin,字符串名);

2.字符数组读:

cin.getline(数组名,数组大小);

理解了怎样读空格,现在我们来写程序吧!


 1.字符串

 


1.变量
#include<bits/stdc++.h>
using namespace std;
string s;
int cnt;
int main()
{
	
}

s:字符串。

cnt:空格数量 。


2.输入 
#include<bits/stdc++.h>
using namespace std;
string s;
int cnt;
int main()
{
	getline(cin,s);
}

用函数getline()读空格。


3.循环判断并计数
#include<bits/stdc++.h>
using namespace std;
string s;
int cnt;
int main()
{
	getline(cin,s);
	for(int i=0;i<s.size();i++){
		if(s[i]==' '){
			cnt++;
		}
	}
}

挨个遍历查找。


4.输出
#include<bits/stdc++.h>
using namespace std;
string s;
int cnt;
int main()
{
	getline(cin,s);
	for(int i=0;i<s.size();i++){
		if(s[i]==' '){
			cnt++;
		}
	}
	cout<<cnt;
}

 直接输出就行了。


2.字符数组

 1.变量
#include<bits/stdc++.h>
using namespace std;
char ch[101];
int cnt;
int main()
{
	
}

 ch[]:字符数组。

cnt:计数器。


2.输入
#include<bits/stdc++.h>
using namespace std;
char ch[101];
int cnt;
int main()
{
	cin.getline(ch,101);
}

用cin.getline()函数。


3.循环判断计数
#include<bits/stdc++.h>
using namespace std;
char ch[101];
int cnt;
int main()
{
	cin.getline(ch,101);
	for(int i=0;i<strlen(ch);i++){
		if(ch[i]==' '){
			cnt++;
		}
	}
}

用strlen()判断数组字符长度。


4.输出
#include<bits/stdc++.h>
using namespace std;
char ch[101];
int cnt;
int main()
{
	cin.getline(ch,101);
	for(int i=0;i<strlen(ch);i++){
		if(ch[i]==' '){
			cnt++;
		}
	}
	cout<<cnt;
}

3.评测结果

1.字符串

 


2.字符数组


4.完整程序


1.字符串

 #include<bits/stdc++.h>
using namespace std;
string s;
int cnt;
int main()
{
    getline(cin,s);
    for(int i=0;i<s.size();i++){
        if(s[i]==' '){
            cnt++;
        }
    }
    cout<<cnt;
}

2.字符数组

 #include<bits/stdc++.h>
using namespace std;
char ch[101];
int cnt;
int main()
{
    cin.getline(ch,101);
    for(int i=0;i<strlen(ch);i++){
        if(ch[i]==' '){
            cnt++;
        }
    }
    cout<<cnt;
}



谢谢大家,给个赞呗!

  • 23
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值