Standard Template Library ~string

C++提供了一个处理字符串的标准类,它被定义在string里面,string类的对象可以通过C++的运算符进行操作,使用string是必须包括头文件string

string类对象可以用构造函数进行初始化,例如:

string s1("hello, world");
string s2="hello, world";

当然的话,也可以定义一个空字符

 

string类中重载了=、+、+=、比较符号、[]和输入输出符号

+ 号表示拼接两个字符串

[]的重载是字符串对象就可以作为字符数组来使用

除此之外, string中还定义了一组成员函数:

函数

作用

substr(start,len)

取子串

capacity()

字符串对象的容量

length()

字符串的长度

find()

查找字符串s在当前串中的位置

insert(pos, s)

在当前字符串的位置pos前插入字符串s

下面是这些函数的实际运用:

#include<iostream>
#include<string>
using namespace std;

int main() {
	string  str("Hello,world");
	cout << "The length of str is :" << str.length() << endl;
	cout << "The capacity of str is :" << str.capacity() << endl;
	cout <<"The start position of world is : " <<str.find("world") << endl;
	cout << "Get the string which begins with 1, and length is: " << str.substr(0, 5) << endl;
	cout << "After insert \"your\" at 6, the new string is : "<< str.insert(6,"your ")<< endl;
	return 0;
}

运行之后程序的输出为:

The length of str is :11
The capacity of str is :15
The start position of world is : 6
Get the string which begins with 1, and length is: Hello
After insert "your" at 6, the new string is : Hello,your world

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值