C++ string

来源:互联网 发布:2015网络热词 编辑:程序博客网 时间:2024/06/05 02:30

String
查找是否含有子字符串
string::size_type idx;
idx=a.find(b);//在a中查找b.
if(idx == string::npos )//不存在。
cout << “not found\n”;
从指定位置开始查找
a.find(i);//查找 ACSII为i的字符。
string st1(“babbabab”);
cout << st1.find(‘a’, 2) << endl;//4 在st1中,从位置2(b,包括位置2)开始,查找字符a,返回首次匹配的位置,若匹配失败,返回npos
cout << (st1.find(‘c’, 0) == -1) << endl;//1
cout << (st1.find(‘c’, 0) == 4294967295) << endl;//1 两句均输出1,原因是计算机中-1和4294967295都表示为32个1(二进制)
//cout << st1.rfind(‘a’,7) << endl;//6 从指定位置向前查找
/*while(a.find(“10”) != -1)(是否含有)或
if (a.find(“2”) != a.npos)
cout << “aaa” << endl;
翻转函数
rerse(mystring.begin(), mystring.end()); 头文件?#include

删除第几个元素
a.erase(a.begin()+i);

替换函数
用str替换指定字符串从起始位置pos开始长度为len的字符
string ori = “his name is Tom”;
string fnd = “Tom”;
string rep = “Jack”;
ori=ori.replace(ori.find(fnd), fnd.length(), rep);

获取子串
int pos = a.find(“-“); 返回位置
sub=a.substr(0, pos); 0-pos位置的子串。
std::string str2 = str.substr (3,5); // “think”

std::size_t pos = str.find(“live”); // position of “live” in str

std::string str3 = str.substr (pos); // get from “live” to the end
string a=”hello”;
string b=a.substr(1,2); //el //从1到后面2个字符
a.substr(2); //llo
a.find(a[1],1); //1

string 添加字符
str.append(str2); // “Writing ”
str.append(str3,6,3); // “10 ”
str.append(“dots are cool”,5); // “dots ”
str.append(“here: “); // “here: ”
str.append(10,’.’); // “……….”
str.append(str3.begin()+8,str3.end()); // ” and then 5 more”
str.append<int>(5,0x2E); // “…..”
String:
string a = “abc”;
char b = ‘d’;
string c = “ddd”;
a.append(c);
a += b;
a += c;
可逆序存储

str.clear(); 清空
str.empty(); 判空

int转string
int n = 0;
std::stringstream ss;
std::string str;
ss>>str;
string转int
std::string str = “123”;
int n = atoi(str.c_str());

原创粉丝点击