string搜索操作:
//搜索操作返回指定字符出现的下标,如果未找到则返回npos。
s.find(args); //查找s中args第一次出现的位置
s.rfind(args); //查找s中args最后一次出现的位置
s.find_first_of(args); //在s中寻找args中任何一个字符最后一次出现的位置。
s.find_last_of(args); //在s中查找args中任何一个字符最后一次出现的位置。
s.find_first_not_of(args); //在s中查找第一个不在args中出现的位置。
s.find_last_not_of(args); //在s中寻找最后一个不在args中出现的字符。
练习9.47:编写程序,首先查找string“abc3d7R4E6”中的每个数字字符,然后查找其中每个字母字符。编写两个版本的程序,第一个要使用find_first_of,第二个要使用find_first_not_of.
用find_first_of的情况
string st = "ab2c3d7R4E6";
string mun = "0123456789";
string alfa = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string::size_type pos = 0;
while((pos=st.find_first_of(mun, pos)) != string::npos){
cout<<st[pos]<<endl;
++pos;
}
pos = 0;
while((pos=st.find_first_of(alfa, pos)) != string::npos){
cout<<st[pos]<<endl;
++pos;
}
用find_first_not_of的情况。
string st = "ab2c3d7R4E6";
string mun = "0123456789";
string alfa = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string::size_type pos = 0;
while ((pos = st.find_first_not_of(alfa, pos)) != string::npos){
cout << st[pos] << endl;
++pos;
}
pos = 0;
while ((pos = st.find_first_not_of(mun, pos)) != string::npos){
cout << st[pos] << endl;
++pos;
}
练习9.48:假定name和numbers的定义如325页所示,numbers.find(name)返回什么?
string numbers("0123456789"), name("r2d2");
因为numbers中不存在和name中重合的字符串所以,返回string::npos;
练习9.49:如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender),如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头部分的单词。
string alfa = "acemnorsuvwxyz";
string input;
string best_long;
string curr;
cin >> input;
for (string::size_type i = 0; i < input.size(); i++){
if (alfa.find(input[i]) != string::npos){
curr = curr + input[i];
}
else{
if (curr.size() > best_long.size())
best_long = curr;
curr.erase(0);
}
}
if (curr.size() > best_long.size())
best_long = curr;
cout << best_long << endl;