1.str.substr(int a, int b) –从下标为a的位置(0开始)截取b个长度的字符串
注意:a不能越界 但b可以超过原字符串的长度 超过默认截取从a位置开始的全部字符串
第二个参数不写表示从a位置开始截取后面全部的字符串
string str;
str = "abcd"; // abcd
cout << str.substr(0, 3); // abc
cout << str.substr(0, 10000); // abcd
cout << str.substr(1, 10000); // bcd
cout << str.substr(1); //bcd
2.str.find(str s)-在str里寻找子串s
找到了返回字符串s第一个字符对应str的位置下标(0开始)找不到返回string::npos
string str = "abcd", s1 = "bcd", s2 = "bce";
if (str.find(s1) != string ::npos) //Yes
{
cout << "Yes" << endl;
}
else cout << "No" << endl;
if (str.find(s2) != string ::npos) //No
{
cout << "Yes" << endl;
}
else cout << "No" << endl;
3.to_string(int x) //可以将整数x转换成字符串, x可以是整数、负数、小数
注意 x是小数的时候转换成字符串会在小数后补0凑足6位
string str;
int a = 3, b = -4;
double c = 3.1, d = -3.75;
str = to_string(a);
cout << str << endl; //3
str = to_string(b);
cout << str << endl; //-4
str = to_string(c);
cout << str << endl; //3.100000
str = to_string(d);
cout << str << endl; //-3.750000
4.sscanf(str.c_str(), “字符串格式”, &变量名)
记得加str.c_str()
从左往右看
string str;
str = "12:56:38";
int h, m, s;
//从左往右看:从12:56:38字符串中提取时分秒给h, m, s
sscanf(str.c_str(), "%02d:%02d:%02d", &h, &m, &s);
cout << h << ' ' << m << ' ' << s; //12 56 38
5.sprintf(str, “字符串格式”, 变量名)
注意 str是字符数组 不能是字符串!!
从右往左看
char str[30];
int h = 12, m = 56, s = 58;
//从右往左看, 将h, m, s变成人们可读的模式 12:56:38
sprintf(str, "%02d:%02d:%02d", h, m, s);
cout << str << endl; //12:56:38
6.string和char数组的输出
string只能通过cin输出 如果想通过printf以%s的格式输出 需要借助str.c_str()
char数组可以通过cin和printf直接输出
可以直接将char数组赋值给string
char c[27];
for (int i = 0; i < 26; i ++) c[i] = i + 65;
string str;
str = "5678";
cout << c << endl; //ABCD.....XYZ
printf("%s\n", c); //ABCD.....XYZ
cout << str << endl; //5678
printf("%s\n", str.c_str()); //5678
str = c;
cout << str << endl; //ABCD.....XYZ
printf("%s\n", str.c_str()); //ABCD.....XYZ