7-26 单词长度
题目链接-7-26 单词长度
解题思路
- 用正则表达式将单词间多个空格转化为单个空格,再去除句头句尾和
.
前的空格 - 特判字符串s长度为1的情况,说明只有一个
.
,所以没有输出 - 然后用
istringstream
依次读入单词,并输出单词长度 - 读入最后一个字符串时因为
.
,长度要减1 istringstream
类用于执行C++风格的串流的输入操作,头文件为<sstream>
,istringstream
以空格作为字符串分隔符- 具体操作及解析见代码
附上代码
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
using namespace std;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+5;
typedef long long ll;
typedef pair<int,int> PII;
string s,t;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
getline(cin,s);
s=regex_replace(s,regex("(\\s+)")," ");//将多个空格转化为单个空格
if(s.front()== ' ')
s.erase(s.begin());//去除句首空格
if(s.back()==' ')
s.pop_back();//去除句尾空格
s=regex_replace(s,regex("( \\.)"),".");//去除.前空格
if(s.length()==1){//如果字符串s长度为1
return 0;//说明只有一个.,所以没有输出
}
istringstream in(s);//构造一个字符串输入流
while(in>>t){//从输入流中读入一个字符串,遇到空格结束
if(*t.rbegin()=='.')
cout<<t.length()-1;
else
cout<<t.length()<<" ";
}
return 0;
}