二十一、标准库类型string的使用、string类介绍、string对象的构造和初始化、string常用成员函数

本文深入探讨了 C++ 中 string 类的基本概念、构造与初始化方式,以及常用成员函数的应用实例,帮助读者理解如何高效地使用 string 类进行字符串操作。

一、string类介绍

string类型是长度可变的字符串,C++标准库将负责管理与存储字符相关的内存,以及提供各种有用的操作
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
要使用string类型对象,必须包含相关头文件
#include<string>
usingstd::string;

二、string对象的构造和初始化

string常用初始化例子:

#include <iostream>
#include <string>
using namespace std;
int main()
{
	string a1("abcdefg");
	cout<<a1<<endl;
	basic_string<char> str;
	string a2("abce",3);
	cout<<a2<<endl;
	string a3(a1,1,3);
	cout<<a3<<endl;

	//迭代器初始化
	string::iterator first = a1.begin() + 1;
	string::iterator last = a1.begin() + 5;
	string a4(first, last);		//[first, last)
	cout<<a4<<endl;
	return 0;
}

三、string常用的成员函数

常用的成员函数使用:

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

int main(void)
{
	string s1("abcdefdg");
	cout<<s1.size()<<endl;
	cout<<s1.length()<<endl;
	cout<<s1.empty()<<endl;

	cout<<s1.substr(1,2)<<endl;
	cout<<s1.substr(1)<<endl;

	string::size_type pos = s1.find('d', 1);
	if (pos == string::npos) cout<<"not found"<<endl;
	else cout<<"pos="<<pos<<endl;

	pos = s1.rfind('d');
	if (pos == string::npos) cout<<"not found"<<endl;
	else cout<<"pos="<<pos<<endl;
	s1.replace(2, 2, "AAAAAA");
	cout<<s1<<endl;

	s1 = "abcdefg";
	s1.replace(s1.begin()+1, s1.begin()+4, "AAAAAA");
	cout<<s1<<endl;

	string s2 = "xyzabc";
	s2.insert(2,"MMMM");
	cout<<s2<<endl;
	s2.append("6666");
	cout<<s2<<endl;

	string s3="111";
	s2.swap(s3);
	cout<<s2<<endl;
	cout<<s3<<endl;

	//find_firset_of实现的是strinfo中第一个在strset中出现的位置
	string strinfo=" //*---Hello World!......------";
	string strset= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	string::size_type first = strinfo.find_first_of(strset);
	if(first == string::npos) 
		cout<<"not find any characters"<<endl; 
	string::size_type last = strinfo.find_last_of(strset);
	if(last == string::npos)
		cout<<"not find any characters"<<endl;
	cout << strinfo.substr(first, last - first + 1)<<endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值