C++String类

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++String类

ALL IN C   2022-05-22 我要评论

一、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=0,int 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 数组存储,字符串数组的话,效率即高又灵活。

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们