首页 > 代码库 > [C++] string

[C++] string

int2string

在#include<string>中自带函数 to_string();

技术分享

对于自写to_string函数,可以采用stringstream.

int a = 10;
stringstream b;
b<<a;
string c = b.str();

#include<sstream>

在循环中,或者重复,使用stringstream时,要先清空!!!

stringstream b;
b.clear();b.str("");    //清空

在stringstream中,.clear仅仅是清空stringstream的状态(如出错等状态信息),清空内容还是需要.str("");方法。

 

string2int

string a = "234";
int b = atoi(a.c_str());
cout<<b;

在C++中更推荐使用流对象来实现类型转换。

string a = "123";    //char* a = "213";
stringstream c(a);
int e = 0;
c >> e;

 

std::basic_string::find

#include <string>
#include <iostream> void print(std::string::size_type n, std::string const &s) { if (n == std::string::npos) { std::cout << "not found\n"; } else { std::cout << "found: " << s.substr(n) << ‘\n‘; } } int main() { std::string::size_type n; std::string const s = "This is a string"; // search from beginning of string n = s.find("is"); print(n, s); // search from position 5 n = s.find("is", 5); print(n, s); // find a single character n = s.find(‘a‘); print(n, s); // find a single character n = s.find(‘q‘); print(n, s); }

found: is is a string
found: is a string
found: a string
not found

 

[C++] string