字符串

一.basic_string模板

•C++中的string实际上是basic_string模板被char类型参数实例化后的类型别名
–template

二.字符串实例化

•在栈中隐式实例化
string str;
string str ("Hello, World !");

•在栈中显式实例化
string str = string ();
string str = string ("Hello, World !");

•在堆中实例化
string* str = new string;
string* str = new string ();
string* str = new string ("Hello, World !");

三.C字符串与C++字符串

•C++的string支持源自C风格字符指针的隐式类型转换
string str = "Hello, World !";
char const* pc = "Hello, World !"; 4
string str = pc;
char sa[] = "Hello, World !"; 
string str = sa;

•C++的string提供了获取C风格字符指针的成员函数
char const* pc = str.c_str ();
c_str()返回字符串对象中用于存放其字符内容的内存地址

四.字符串运算

1)赋值、拼接与复合赋值
•赋值

string s1 = "hello", s2 = "world"; 
s1 = s2; 
cout << s1 << endl; // world

•拼接

string s1 = "hello", s2 = "world"; 
string s3 = s1 + s2; 
cout << s3 << endl; // helloworld

•复合赋值

string s1 = "hello", s2 = "world"; 
s1 += s2; 
cout << s1 << endl; // helloworld
 ``` 
 2)关系比较
 ```
•</<=/==/!=/>=/>
–string s1 = "zhangfei"; 
 string s2 = "zhaoyun"; 
 if (s1 == s2) 
    cout << s1 << "==" << s2 << endl; 
 else if (s1 < s2) 
    cout << s1 << "<" << s2 << endl; 
 else 
    cout << s1 << ">" << s2 << endl;

•string类型的关系比较区分大小写
–string ("zhangfei") < string ("zhaoyun")
–string ("zhangfei") > string ("zhaOyun")

3)下标访问

•通过下标访问字符串中的单个字符
–string str = "hello, world !"; 
 for (size_t i = 0; i < str.length (); ++i) 
    if ('a' <= str[i] && str[i] <= 'z') 
        str[i] -= 'a' - 'A'; 
cout << str << endl; // HELLO, WORLD !

•不检查下标越界
–string str = "hello, world !"; str[14] = 'A'; // 未定义

五.字符串的大小

1)获取和改变大小

•获取大小,即字符数
–size_type size (void) const;
–size_type length (void) const;
–不包括结尾空字符

•改变大小,可增可减
–void resize (size_type size, const char& ch = '\0');
–新增部分用第二个参数所表示的字符初始化,缺省空字符

•清空字符串内容
–void clear (void);

•判断是否为空,空返回true,不空返回falsebool empty (void) const;

std::cout << str1.capacity() << std::endl;
//获取的是字符串最多容纳的字符数。由于字符串可以动态改变,所以在向字符串添加字符时,字符串会变长,但不是添加一个字符就只变长一个字节,而是变长单位长度的字节数,这样做的好处是避免频繁内存操作,提高效率。

str1.reserve(50);
//可以指定字符串的容量。

2)字符串和字符串对象的大小
•字符串大小指其实际容纳的字符数,不包括结尾空字符
•字符串对象大小指该对象本身的字节数,不包括其内容
•多数C++实现,string实际上只包含一个char*类型的非静态成员变量,该变量保存一个以空字符结尾的字符数组首地址。
因此,一个string对象的大小,实际上就是它唯一一个非静态成员变量的大小,4个字节(32位系统)

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值