string C++

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;
}

run the above code here

 

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;
}

run the above code here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值