C++笔记 String

C++笔记 String

String介绍:

  String是C++中的标准库,用来处理字符串。个人理解代替之前C中char较为底层的处理方式。

初始化方法:

方法1:
#include <string>
using namespace std;
int main(){
	string s1;
	string s2 = "123";
	string s3("123");
	string s4{"123"};
}
方法2:
#include <iostream>
#include <string>
using namespace std;
int main(){
	//通过生成方式
	string s1(5,'1');
	cout << s1 << endl;
}

结果:
在这里插入图片描述

String常用方法:

 size()与length()使用。两者相同。

#include <string>
using namespace std;
int main(){
	string s1 = "123";
	cout << s1.size() <<"\n" 
		<< s1 << "\n"
		<< s1.length()
		<<endl;
}

在这里插入图片描述

String源码size()对比length():

在这里插入图片描述
 两者代码一致。

String类型访问:

 可以通过下标索引:

#include <string>
using namespace std;
int main(){
	string s1 = "123";
	cout << s1[1] << endl;
}

String类型拼接:

#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1 = "123";
	string s2 = "321";
	s2 = s1 + s2;
	cout << s2 << endl;
}

在这里插入图片描述

String类型拷贝:

#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1 = "123";
	string s2 = "321";
	s2 = s1 ;
	cout << s2 << endl;
}

在这里插入图片描述
 可以看到地址没发生变化不存在其他语言中的伪拷贝现象。

String类型比较

#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1 = "123";
	string s2 = "123";
	if (s1 == s2)
		cout << true << endl;	
}

在这里插入图片描述

String类型与C语言中的字符串兼容

#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1 = "123";
	const char* point;
	point = s1.c_str();
	cout << point << endl;
}

在这里插入图片描述

C语言字符串初始化
#include <iostream>
#include <string>
using namespace std;
int main(){
	char* str = "str";
	string s1(str);
	cout << s1 << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值