练习9.47:
编写程序,首先查找string “ab2c3d7R4E6”中的每个数字字符,然后查找其中每个字母字符。编写两个版本的程序,第一个要使用find_first_of, 第二个要使用find_first_not_of。
解答:
#include <iostream>
#include <string>
using namespace std;
void myFind1(const string& str){
string::size_type pos = 0;
string number("0123456789");
while((pos = str.find_first_of(number, pos)) != string::npos){
cout << "found number at index:" << pos;
cout << " element is " << str.at(pos) << endl;
++pos;
}
}
void myFind2(const string& str){
string::size_type pos = 0;
string number("0123456789");
while((pos = str.find_first_not_of(number, pos)) != string::npos){
cout << "found character at index:" << pos;
cout << " element is " << str.at(pos) << endl;
++pos;
}
}
int main(){
string mystr("ab2c3d7R4E6");
myFind1(mystr);
myFind2(mystr);
}
练习9.48:
假定name和numbers的定义如325页所示,numbers.find(name)返回什么?
解答:
这里需要引用一下这两个函数的动作定义:
【引用】s.find(arg) 查找s中args第一次出现的位置
【引用】s.find_fisrt_of(arg) 在s中查找args中任何一个字符第一次出现的位置
我们在325页中可以看到number为“0123456789”, name为“r2d2”。
所以,使用find_fisrt_of会返回1.
而使用find将会返回-1,也就是string::npos。
这里相当于number全字符匹配name,在name里面无法找到number的字符串,所以会以npos作为返回值。
练习9.49:
如果一个字母延伸到中线之上,如d或f,则称其为有是上出头部分(asender)。如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。编写程序,读入一个单词文件,输出最长的既不包括上出头部分,也不包括下出头部分的单词。
解答:
#include <iostream>
#include <string>
using namespace std;
const string ascender_and_desender("bdfghijkpqy");
void myNotInc(const string& str){ // 参考326页的程序写出
string::size_type pos = 0;
while((pos = str.find_first_not_of(ascender_and_desender, pos)) != string::npos){
cout << str.at(pos);
++pos;
}
cout << endl;
}
int main(){
string mystr("ab2c3d7R4E6"); // 使用上题的字符串来模拟单词文件中的内容
myNotInc(mystr);
}