string类型说明:
string并不是C++语言的基本类型,而是C++标准库中声明的一个字符串类,用这种类可定义对象
string类的定义:
string 对象名(初始化数据);
string类型变量的运算:
str1 = str2;//字符串的复制
str1 += str2;//字符串的连接
k = (str1 > str2);//类似关系运算符有"<","==","!=",">=","<="
string类型数组
string name[5]={"Zhang","Li","Fan","Wang","Tan"};//每一个字符串元素中只包含字符串本身的字符而不包含'\0'
string类的构造函数原型:
string();//默认构造函数
string(const char *s);//赋值,string str1("HELLO");
string(const string& str);//赋值,string str2(str1);
string(const char *s,unsigned n);//将s指向的字符串的前n个字符赋值给新串
string(const string& str,unsigned pos,unsigned n);//将s指向的字符串的pos位置到pos+n位置的部分字符串赋给新串
string(unsigned n,char c);//将字符c重复n次,构成新串
#include <string>//头文件为<string>
#include <iostream>
using namespace std;
int main()
{
string str;
string str1("hello");
string str2(str1);
string str3("hello",2);
string str4("hello",1,3);//注意角标!
string str5(5,'h');
cout<<"str1="<<str1<<endl;
cout<<"str2="<<str2<<endl;
cout<<"str3="<<str3<<endl;
cout<<"str4="<<str4<<endl;
cout<<"str5="<<str5<<endl;
}
运行结果:
str1=hello
str2=hello
str3=he
str4=ell
str5=hhhhh
string类的大小属性函数:
unsigned capacity();//返回容量,即默认内存空间大小
unsigned size();//返回字符串大小
unsigned length();//返回字符串的长度
bool empty();//返回当前字符串是否存储字符
void resize(unsigned len,char c);//重置字符串的长度,并用字符c填充不足的部分
int main()
{
string str("hello");
cout<<"str capacity ="<<str.capacity()<<endl;
cout<<"str size ="<<str.size()<<endl;
cout<<"str length ="<<str.length()<<endl;
cout<<"str bool ="<<str.empty()<<endl;
str.resize(10,'w');
cout<<"str resize ="<<str<<endl;
}
运行结果:
str capacity =5
str size =5
str length =5
str bool =0
str resize =hellowwwww
string类字符及字符序列访问属性函数
char &at(unsigned n);//返回字符串角标为n的字符
string substr(unsigned pos,unsigned n);//返回字符串从角标为pos开始的n个字符的字串
int main()
{
string str("hello");
cout<<"字符串str第2个字符:"<<str.at(2)<<endl;//注意角标!
cout<<"字符串str第2-4个字符:"<<str.substr(2,4)<<endl;//注意角标!
}
运行结果:
字符串str第2个字符:l
字符串str第2-4个字符:llo
版权声明:本文为qq_43341057原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。