练习9.47:编写程序,首先查找string“abc3d7R4E6”中的每个数字字符,然后查找其中每个字母字符。编写两个版本的程序,第一个要使用find_first_of,第二个要使用find_first_not_of.
答:见程序练习9.47
练习9.48:假定name和numbers的定义如325页所示,numbers.find(name)返回什么?
答:返回string::npos(参考P325,9.5.3)
练习9.49:如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender),如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头部分的单词。
答:见练习9.49.cpp
练习9.47
/*
*练习9.47
*日期:2015/8/7
*问题描述:练习9.47:编写程序,首先查找string"abc3d7R4E6"中的每个数字字符,然后查找其中每个字母字符。编写两个版本的程序,第一个要使用find_first_of,第二个要使用find_first_not_of.
*说明;字符的查找
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*/
#include <iostream>
#include <string>
using namespace std;
void use_find_first_of(string str, string find_str)
{
auto pos = 0;
while((pos = str.find_first_of(find_str,pos)) != string::npos)
{
cout << "char: " << str[pos] << " index: " << pos << endl;
++pos;
}
cout << endl;
}
void use_find_first_not_of(string str , string not_find_str)
{
auto pos = 0;
while((pos = str.find_first_not_of(not_find_str,pos)) != string::npos)
{
cout << "position: " << pos << " char: " << str[pos] << endl;
++pos;
}
cout << endl;
}
int main()
{
string str = "abc3d7R4E6";
string numbers = "0123456789";
string letters = "abcdRE";
use_find_first_of(str, numbers);
use_find_first_of(str, letters);
use_find_first_not_of(str, letters);
use_find_first_not_of(str, numbers);
return 0;
}
练习9.48
#include <iostream>
#include <string>
using namespace std;
int main()
{
string numbers("0123456789"), name("r2d2");
//cout << numbers.find(name) << endl;
auto pos = numbers.find(name);
cout << pos << endl;
return 0;
}
练习9.49
/*
*练习9.49
*日期:2015/8/7
*问题描述:练习9.49:如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender),如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头部分的单词。
*说明:弄清题意再下手,不然想了半天,发现题目都没读对,怎么可能做出来
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*/
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
void output_max_subword(string filename)
{
string s = "bdfhkltgjpqy"; //找出上下头的字母
vector<string> vec;
string word;
ifstream stream(filename); //读入单词文件
while(!stream.eof())
{
stream >> word;
auto pos = 0;
pos = word.find_first_of(s,pos);
if(pos == string::npos)
vec.push_back(word); //将不包含上下头的字母放进容器
}
auto count = 0;
for(auto i = 0; i != vec.size(); ++i) //找尺寸最大的字符串输出
{
auto max = vec[0].size();
if(vec[i].size() >= max)
count = i;
}
cout << vec[count] << endl;
}
int main()
{
output_max_subword("word.txt");
return 0;
}