题目描述

编一个程序,读入用户输入的,以“.”结尾的一行文字,统计一共有多少个单词,并分别输出每个单词含有多少个字符。 (凡是以一个或多个空格隔开的部分就为一个单词)

输入描述

输入包括1行字符串,以“.”结束,字符串中包含多个单词,单词之间以一个或多个空格隔开。

输出描述

可能有多组测试数据,对于每组数据,
输出字符串中每个单词包含的字母的个数。

示例
输入
hello how are you.
输出
5 3 3 3
总结

利用string,vector会大大简化代码量。
getline(cin,str);忽略空格,读一行,直到遇到换行结束(也就是回车)。
id=str.find(".");定位字串在主串的位置。
id.push_back(x);将x添加到vector的尾部,作为一个元素。

原题链接
Code
/* 思路; 1、定位第一个字母的位置和最后一个‘.’ 的位置 2、确定每个空格所在的位置 3、输出 第一个空格的位置减去第一个字母的位置+1,中间的空格位置减去前一个空格的位置输出,最后一个‘.’的位置减去最后一个空格的位置 */
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int getFistCharacter(string str)
{
   
	for (int i = 0; i < str.length(); i++)
	{
   
		if (str[i] >= 'A' || str[i] <= 'Z' || str[i] >= 'a' || str[i] <= 'z')
			return i;
	}
}
void getBlank(vector<int> &id,string str,int first)
{
   
	for (int i = first; i < str.length(); i++)
	{
   
		if (str[i] == ' ')
			id.push_back(i);
	}
}
int main()
{
   
	int firstCharacter, endDot;//分别定位一个字母的位置和最后一个'.'的位置
	string str;
	vector<int> id;
	getline(cin, str);
	firstCharacter = getFistCharacter(str);
	endDot = str.find(".");
	getBlank(id, str, firstCharacter);//将每个空格的位置保存再数组id中
	int idSize = id.size();
	if (idSize == 0)//没有空格的情况
		cout << endDot - firstCharacter;
	else if (idSize == 1)
		cout << id[0] - firstCharacter << " " << endDot - id[0] - 1;
	else
	{
   
		cout << id[0] - firstCharacter << " ";
		for (int i = 1; i < idSize; i++)
		{
   
			cout << id[i] - id[i - 1] - 1 << " ";
		}
		cout << endDot - id[idSize - 1] - 1;
	}
	return 0;
}