求助一下关于字符串的一道题
输入一行字符,统计其中有多少个单词,单词之间用空格隔开 print(len(input().split())) 永恒的蓝色梦想 发表于 2020-7-20 16:07这是 C/C++ 版块{:10_277:} zltzlt 发表于 2020-7-20 16:08
这是 C/C++ 版块
这是我在网上看到的一道题scanf不是读到空格就会停止吗这个题用C语言不能实现吗 本帖最后由 永恒的蓝色梦想 于 2020-7-20 16:49 编辑
15533617457 发表于 2020-7-20 16:11
这是我在网上看到的一道题scanf不是读到空格就会停止吗这个题用C语言不能实现吗
#include<iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
bool prev_is_space = true;
unsigned count = 0;
for (;;) {
switch (cin.get()) {
case 0:
case -1:
case '\r':
case '\n':
cout << count << endl;
return 0;
case ' ':
prev_is_space = true;
break;
default:
if (prev_is_space) {
++count;
}
prev_is_space = false;
}
}
} 本帖最后由 巴巴鲁 于 2020-7-20 18:43 编辑
#include <stdio.h>
int main(void)
{
char ch;
int count = 1; // 没有空格1个单词
while((ch = getchar()) != '\n')
{
if(ch == ' ')
{
count++;
}
}
printf("%d",count);
return 0;
}
你这个问题清晰明了。简单高效!统计多少个空格,然后加1就行了。、
可以用变量,初始赋值为1。因为一输入就有一个单词了。至于那些神经病直接回车的,忽略他吧!
让我们来if!:
if(ch==' ')n++;完了!最后printf进行输出打印。当然,你得先定义变量。比如:
char ch;int n=1;
然后啊,一个个地getchar()。
do{
ch=getchar();
if (ch==' ') n++;
}
while((ch==getchar)!='\n');//好久没用过do-while了,不知道后面有没有分号
printf("一共有%d个单词",n); #include <iostream>
using namespace std;
int main(){
int cnt = 0;
char ch;
while(cin.get(ch)){
if(ch=='\n')break;
if((ch>='a'&&ch<='z'||ch>='A'&&ch<='Z')&&(cin.peek()==' '||cin.peek()=='\n'))
++cnt;
}
cout << cnt;
return 0;
} 本帖最后由 baige 于 2020-7-24 10:34 编辑
#include <iostream>
#include <string>
using namespace std;
int main(){
string text, temp = "";
getline(cin,text);
text += ' ';
int cnt = 0;
int length = text.size();
for(int i = 0; i < length; ++i){
if(text==' '){
if(temp.size()==0)
continue;
++cnt;
cout << cnt << temp << " ";
temp = "";
}
else {
temp += text;
}
}
cout << endl << cnt;
return 0;
}
首先遍历字符数组,查找空格(strstr,strtok,等函数,或者自己写!),(需要单独处理亦可以使用memmove等函数复制一份子数组)不管有没有,主要难点就是怎么判断它是一个单词!
页:
[1]