首页 > 其他分享 >7-3 统计一行文本的单词个数 (15 point(s))

7-3 统计一行文本的单词个数 (15 point(s))

时间:2023-01-04 18:35:23浏览次数:77  
标签:空格 15 temp point st 单词 re split


本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。

输入格式:
输入给出一行字符。

输出格式:
在一行中输出单词个数。

输入样例:

Let's go to room 209.

输出样例:

5

方法一:

#python
s = input().split()
print(len(s))

方法二:

//c++
#include<iostream>
#include<vector>

using namespace std;
vector<string> split(string st, char sign){
vector<string> re;
for(int i = 0; i < st.size(); i++){
string temp = "";
while(st[i] != sign &&i < st.size()){
temp += st[i];
i++;
}
//去除多余空格
while(isspace(st[i]))i++;
re.push_back(temp);
}
return re;
}
int main(){
string st;
getline(cin, st);
//去除开头空格
while(isspace(st.front()))st.erase(st.begin());
vector<string> re = split(st,' ');
cout << re.size();
return 0;
}


标签:空格,15,temp,point,st,单词,re,split
From: https://blog.51cto.com/u_14597003/5989175

相关文章