我在做THIS UVa 问题,它接受以下输入:
This is fun-
ny! Mr.P and I've never seen
this ice-cream flavour
before.Crazy eh?
#
This is fun-
ny! Mr.P and I've never seen
this ice-cream flavour
before.Crazy eh?
#
并产生这个输出:
1 1
2 3
3 2
4 3
5 3
6 1
7 1
8 1
1 1
2 3
3 2
4 3
5 3
6 1
7 1
8 1
在输入中,# 划分大小写。我应该获取每个单词的长度并计算每个不同长度的频率(如您在输出中看到的,长度为 1 的单词出现一次,长度 2 出现三次,长度 3 出现两次,依此类推)。
我的问题是:在 cin 中读取时,before.Crazy
算作一个单词,因为没有空格将它们分开。然后它应该像在某些标点符号上拆分字符串一样简单(例如 {".",",","!","?"}
)...但是 C++ 似乎没有简单的方法来拆分字符串。
那么,我的问题是:如何拆分字符串并将每个返回的字符串发送到处理其余问题的函数?
这是我的代码:
int main()
{
string input="";
while(cin.peek()!=-1)
{
while(cin >> input && input!="#")
{
lengthFrequency(input);
cout << input << " " << input.length() << endl;
}
if(cin.peek()!=-1) cout << endl;
lengthFrequencies.clear();
}
return 0;
}
lengthFrequency
是 map<int,int>
.
最佳答案
您可以使用 std::locale
重新定义流认为是空白字符的内容自定义 std::ctype<char>
方面。下面是相应的代码,它并没有完全完成分配,但演示了如何使用 facet:
#include <algorithm>
#include <iostream>
#include <locale>
#include <string>
struct ctype
: std::ctype<char>
{
typedef std::ctype<char> base;
static base::mask const* make_table(char const* spaces,
base::mask* table)
{
base::mask const* classic(base::classic_table());
std::copy(classic, classic + base::table_size, table);
for (; *spaces; ++spaces) {
table[int(*spaces)] |= base::space;
}
return table;
}
ctype(char const* spaces)
: base(make_table(spaces, table))
{
}
base::mask table[base::table_size];
};
int main()
{
std::cin.imbue(std::locale(std::locale(), new ctype(".,!?")));
for (std::string s; std::cin >> s; ) {
std::cout << "s='" << s << "'\n";
}
}
关于c++ - 在 C++ 中拆分字符串(使用 cin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579390/