习题9-41
void test941()
{
vector<char> cvec = {'a', 'b', 'c', 'd', 'e'};
string str(cvec.begin(), cvec.end());
cout << str << endl;
}
习题9-42
string str;
str.reserve(100);
char word;
while (cin >> word)
str.push_back(word);
习题9-43
#include <iostream>
#include <string>
using namespace std;
void replace(string& s, const string& oldVal, const string& newVal)
{
auto curr = s.begin();
for (curr; curr != s.end() - oldVal.size(); ++curr)
{
if (oldVal == s.substr(curr - s.begin(), oldVal.size()))
{
curr = s.erase(curr, curr + oldVal.size());
curr = s.insert(curr, newVal.begin(), newVal.end());
curr += newVal.size();
}
}
}
void main()
{
string s("To drive straight thru is a foolish, tho courageous act.");
replace(s, "tho", "though");
replace(s, "thru", "through");
cout << s;
}
习题9-44
#include <iostream>
#include <string>
using namespace std;
void replace(string& s, const string& oldVal, const string& newVal)
{
auto curr = s.begin();
for (curr; curr != s.end() - oldVal.size(); ++curr)
{
if (oldVal == s.substr(curr - s.begin(), oldVal.size()))
{
s.replace(curr,curr+oldVal.size(),newVal);
curr += newVal.size();
}
}
}
void main()
{
string s("To drive straight thru is a foolish, tho courageous act.");
replace(s, "tho", "though");
replace(s, "thru", "through");
cout << s;
}
习题9-45
#include <iostream>
#include <string>
using namespace std;
void replace(string& s, const string& first, const string& last)
{
auto it1 = s.begin();
it1=s.insert(it1, first.begin(),first.end());
s.append(last);
}
void main()
{
string s("John");
replace(s, "Mr", "Jr");
cout << s;
}
习题9-46
#include <iostream>
#include <string>
using namespace std;
void replace(string& s, const string& first, const string& last)
{
s.insert(0, first);
s.insert(s.size(),last);
}
void main()
{
string s("John");
replace(s, "Mr", "Jr");
cout << s;
}
习题9-47
#include <iostream>
#include <string>
using namespace std;
void main()
{
string str = "ab2c3d7R4E6";
string nums = "0123456789";
string::size_type pos=0;
while ((pos = str.find_first_of(nums, pos)) != string::npos)
{
cout << str[pos] << " ";
++pos;
}
pos = 0;
cout << endl;
while ((pos = str.find_first_not_of(nums, pos)) != string::npos)
{
cout << str[pos] << " ";
++pos;
}
}
习题9-48
返回npos,find函数查找指定的字符串(整体查找)
习题9-49
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void find_not_in(const string& s, string& result)
{
string not_in("dfpg");
int size;
if (s.find_first_of(not_in) == string::npos)
{
result = result.size() < s.size() ? s : result;
}
}
void main()
{
ifstream ifs("D:data.txt");
string str1,str2;
while(ifs >> str1)
{
find_not_in(str1, str2);
}
cout << str2 << endl;
}
习题9-50
#include <iostream>
#include <string>
#include<vector>
using namespace std;
void main()
{
vector<string> str{ "1","2","3","4","5.2" };
int sum1 = 0;
double sum2 = 0.0;
for (vector<string>::size_type i = 0; i < str.size(); ++i)
{
sum1 += stoi(str[i]);
sum2 += stod(str[i]);
cout << str[i] << " ";
}
cout << endl;
cout << sum1 << " " << sum2 << endl;
}