【标准库类型string】
string是C++标准库头文件,包含了拟容器class std::string的声明。
1.cstring是C标准库头文件的C++标准库版本, 包含了C风格字符串(NUL即’\0’结尾字符串)相关的一些类型和函数的声明,例如strcmp、strchr、strstr等。
2.castring和string.h的最大区别在于,其中声明的名称都是位于std命名空间中的,而不是后者的全局命名空间。
注意:不能用printf直接输出string,需要写成:printf("%s", s.c_str());
#include
#include
using namespace std;
int main()
{
string s1(); // si = ""
string s2("Hello"); // s2 = "Hello"
string s3(4, 'K'); // s3 = "KKKK"
string s4("12345", 1, 3); // s4 = "234",即 "12345" 的从下标 1 开始,长度为 3 的子串
cout << s1 << " " << s2 << " " << s3 << " " << s4 << endl;
system("pause");
return 0;
}
运行结果:
1 Hello KKKK 234
【string】最简单,最常用的赋值方式:
#include
#include
using namespace std;
int main()
{
string str;
str = "Hello World!";
str += " Okay?";
str = str + " Yes.";
cout << str << endl;
system("pause");
return 0;
}
【.size()】【.length()】
#include
#include
using namespace std;
int main()
{
string str("BaiShiZhiDao.com");
cout << "size: The size of str is " << str.length() << " bytes.\n";
cout << "length: The size of str is " << str.length() << " bytes.\n";
system("pause");
return 0;
}
显示:
size: The size of str is 16 bytes.
length: The size of str is 16 bytes.
【reverse】反转
#include
#include
using namespace std;
int main()
{
string str = "123456789";
reverse(str.begin(), str.end());
cout << str << endl;
system("pause");
return 0;
}
运行结果是:
987654321
【strlen】【strcmp】【strcpy】
strlen(str),求字符串的长度,不含\0。
strcmp(a, b),比较两个字符串的大小,ab返回1。这里的比较方式是字典序!
strcpy(a, b),将字符串b复制给从a开始的字符数组。
#include
#include
using namespace std;
int main()
{
char a[100] = "Hi", b[100];
cout << "strlen=" << strlen(a) << endl; //需要库string.h
strcpy(b, a);
cout << "strcmp=" << strcmp(a, b) << endl;
system("pause");
return 0;
}
运行结果:
strlen=2
strcmp=0
【遍历字符数组的字符】
#include
#include
using namespace std;
int main()
{
char a[100] = "BaiShiZhiDao.com";
int len = strlen(a);
for (int i = 0; i < len; i++)
cout << a[i] << "_";
cout << endl;
system("pause");
return 0;
}
运行结果:
B_a_i_S_h_i_Z_h_i_D_a_o_._c_o_m_