isalnum的函数功能是指出一个字符在运行时字符集中是否为字母数字。也就是这个函数可以帮我们快速判断一个字符是不是字母或数字,而不是其它标点或字符。
使用isalnum需要包含<local>头文件
isalnum第一个参数为需要判断的字符,第二参数为locale("")
运用这个函数,我们可以完成单词统计功能,在有标点的情况下也不怕
EXAMPLE
#include <iostream>
#include <istream>
#include <ostream>
#include <map>
#include <string>
#include <iomanip>
#include <locale>
int main()
{
using namespace std;
map<string,int> counts;
string word;
//从标准输入读取单词,并计算每个单词现的次数
while(cin >> word)
{
string copy;
for(string::iterator w(word.begin()); w != word.end(); ++w)
if(isalnum(*w,locale())) //判断是否为字母或数字
copy.push_back(*w);
else
{
if(! copy.empty())
++counts[copy];
copy.clear();
}
if(! copy.empty())
++counts[copy];
}
int longest(0);
for(map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
{
if(iter->first.size() > longest) //取得单词中最长的一个的长度
longest = iter->first.size();
}
const int count_size(10);
for(map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
cout<< setw(longest) << left <<iter->first //以一定的格式输出
<< "\t"
<< setw(count_size) << right << iter->second << "\n";
map<string,int>::iterator the(counts.find("as"));
if(the == counts.end())
cout<< "the not found!\n";
else
{
cout<< "the occurs " << the->second << " times!\n";
}
}
POSSIBLE OUTPUT