十、C++ 系统String类

十、C++ 系统String类

除了使用字符数组来处理字符串以外,c++引入了字符串类型。可以定义字符串变量。

1.定义及初始化

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

int main()
{
	string str;
	str = "china";
	string str2 = " is great ";
	string str3 = str2;
	cout<<str<<str2<<endl<<str3<<endl;
	return 0;
}

输出结果

2.类型大小

cout<<"sizeof(string) = "<<sizeof(string)<<endl;
cout<<"sizeof(str) = "<<sizeof(str)<<endl;

输出结果

3.常用运算

1.赋值

string str3 = str

2.加法

string combine = str + str2;
cout<<combine<<endl;

3.关系

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

int main()
{
	string s1 = "abcdeg";
	string s2 = "12345";
	if(s1>s2)
		cout<<"s1>s2"<<endl;
	else
		cout<<"s1<s2"<<endl;
	string s3 = s1+s2;
	cout<<s3<<endl;
	return 0;
}

输出结果

4.常见的成员函数

1.下标操作

char & operator[](int n) ;

2.求串大小

int size();

3.返回c串(c语言中的字符串也叫c串)

char *c_str();

4.查找

int find(char c, int pos = 0);
int find(char * s, int pos = 0);
//返回下标值,没有找到返回-1,默认从 0 下标开

5.删除

string &erase(int idx=0int n = npos);
//作用是删除从 idx 开始,往后数 n 位的字符串

6.交换swap

void swap(stirng &s2);

5.string类型数组

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

int main()
{
	string sArray[10] = {
	"0",
	"1",
	"22",
	"333",
	"4444",
	"55555",
	"666666",
	"7777777",
	"88888888",
	"999999999",
	};
	for(int i=0; i<10; i++)
	{
		cout<<sArray[i]<<endl;
	}
	return 0;
}

string 数组是高效的,如果用二维数组来存入字符串数组的话,则容易浪费空间,此时列数是由最长的字符串决定。如果用二级指针申请堆空间,依据大小申请相应的空间,虽然解决了内存浪费的问题,但是操作麻烦。用 string 数组存储,字符串数组的话,效率即高又灵活。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值