Play with Code Then You will Get Better
string::find
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (char c, size_t pos = 0) const;
str.find(1, 2, 3);
在str里面找1,从2(0-indexed)开始找,1的length。
1 could be string, c_str/part of c_str, char
return the position if found
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("0123456");
string s2("2");
auto found = s1.find(s2);
if(found!=string::npos) cout<<"find s2 at "<<found<<endl;
found = s1.find(s2, found+1);
if(found==string::npos) cout<<"cannot find s2"<<endl;
found = s1.find("3");
if(found!=string::npos) cout<<"find 3 at "<<found<<endl;
found = s1.find("3", found+1);
if(found==string::npos) cout<<"cannto find 3"<<endl;
found = s1.find("432", 1, 1);
if(found!=string::npos) cout<<"find 4 at "<<found<<endl;
found = s1.find('3');
if(found!=string::npos) cout<<"find 3 at "<<found<<endl;
found = s1.find('3', found+1);
if(found==string::npos) cout<<"cannot find 3"<<endl;
return 0;
}
string::stoi
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
stoi(str, 1, 2);
convert str to a number of base 2; 1 is the position after the number
return the number after the convertion
#include <iostream>
#include <string>
using namespace std;
int main()
{
string dec = "2001aaaa";
string hex = "40c3zzzz";
string bin = "-10010bbbb";
string random = "0x7fppp";
string not_num = "notnum";
size_t sz;
int dec_num1 = stoi(dec);
int dec_num2 = stoi(dec, &sz);
cout<<dec_num1<<endl;
cout<<dec_num2<<" "<<dec.substr(sz)<<endl;
int hex_num1 = stoi(hex, nullptr, 16);
int hex_num2 = stoi(hex, &sz, 16);
cout<<hex_num1<<endl;
cout<<hex_num2<<" "<<hex.substr(sz)<<endl;
int bin_num1 = stoi(bin, nullptr, 2);
int bin_num2 = stoi(bin, &sz, 2);
cout<<bin_num1<<endl;
cout<<bin_num2<<" "<<bin.substr(sz)<<endl;
int random_num1 = stoi(random, nullptr, 0);
int random_num2 = stoi(random, &sz, 0);
cout<<random_num1<<endl;
cout<<random_num2<<" "<<random.substr(sz)<<endl;
// ERROR
// int not_num1 = stoi(not_num, nullptr, 0);
// cout<<not_num1<<endl;
return 0;
}