C++学习:string的了解

1.string的介绍

#include<string>

对于字符串的操作

自动处理内存的分配和释放

2.string的声明与初始化

1.std::string str1;空的

2.string str2 ="afhsihsa"

3.string str3 = str2

4.string str3 = str2.substr(0,5)
.substr(位置,长度)

5.const char* charArray ="hello"

string str5(charArray);

6.string str6(5,'A');

string(个数,字符);————“AAAAA”

3.基本操作
#include<bits/stdc++.h>
using namespace std;
int main(void){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
char buf[100];
scanf("%s", buf);
string str(buf);
printf("%s",str.c_str);
}

在C++中使用c_std用于将string转换为C风格的字符串进行输出。

1.获取字符串长度

.length

2.拼接字符串

str1 = str+str0

3.字符串查找

.find(****)

4.字符串替换

.replace(字串的起始位置,子串的长度,”替换的内容“)

5.提取子字符串

substr(起始位置,长度)

不要越界

6.字符串比较

str1.compare(str2)

string的遍历

#include<cmath>
#include<bits/stdc++.h>
using namespace std;
int main(void) {
	string str1 = "hello";
	for (int i = 0; i < str1.length(); i++)
		cout << str1[i];
	cout << '\n';
	for (auto i : str1)	
	{
		cout << i;
		i = 'a';
		//不改变str1
	}
	cout << '\n';
	for (auto &i : str1)
	{
		cout << i;
		i = 'a';
		//改变str1
	}
	cout << '\n';
	cout << str1 << endl;
	return 0;
}
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值