9.47
#include <iostream>
#include <string>
using namespace std;
void find_char(string &s, const string &chars)
{
string::size_type pos = 0;
while ((pos = s.find_first_of(chars, pos)) != string::npos) {
cout << "index: " << pos << ", element: " << s[pos] << endl;
++pos;
}
}
void find_not_char(string &s, const string &chars)
{
string::size_type pos = 0;
while ((pos = s.find_first_not_of(chars, pos)) != string::npos) {
cout << "index: " << pos << ", element: " << s[pos] << endl;
++pos;
}
}
int main()
{
string s("ab2c3d7R4E6");
find_char(s, "0123456789");
find_not_char(s, "0123456789");
return 0;
}
9.48 返回npos。s.find(args),args是整体;s.find_frist_of(args), args是字符集合。
9.49
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
string find_word(const vector<string> &svec)
{
string chars("bdfghijklpqty");
string ret;
for (auto s : svec) {
auto pos = s.find_first_of(chars);
if (pos == string::npos && ret.size() < s.size())
ret = s;
}
return ret;
}
int main(int argc, char *argv[])
{
ifstream input(argv[1]);
vector<string> text;
string line, word;
while (getline(input, line)) {
istringstream in(line);
while (in >> word)
text.push_back(word);
}
auto result = find_word(text);
if (!result.size())
cout << "The word doesn't exsit!" << endl;
else
cout << result << endl;
return 0;
}