8.string

在这里插入图片描述

string的初始化

在这里插入图片描述

#include<iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
	//1.字符串的初始化 
 
	// 创建空的字符串
	string s1;
	cout << s1 << endl;


	/*我们知道,字符串常量不可以修改,是一个const型但是,
	我们的str1是一个char*所以需要强制转化*/
	char * str1=(char*)"qwertyuiop";
	string s2(str1);
    cout << s2 << endl;


	//这里也是转化,不过是将左边的s2转化为了和右边一样的类型
	const char* str2 = "123456789";
	string s3(str2);
	cout << s3 << endl;


	//这里为什么要这么做?
	char str3[] = "xpxpxp";
	char* str4 = str3;
	string s4(str3);
	string s5(str4);
	cout << s4 << endl;
	cout << s5 << endl;


	//使用另一个字符串初始化其他字符串
	string s6(s1);
	string s7 = s2;
	cout << s6 << endl;
	cout << s7 << endl;

	//使用n个字符c初始化,后面不是字符串型,是字符型!
	string s8(10,'a');
	cout << s8 << endl;

	char str[4] = { 'q','w','e','r' };
	string s9(str);
	
	cout << s9 << endl;

	//我们发现s9出现乱码了
	//所以推断出string的原理就是从首地址开始读到\0为止!!!!!!!
}

所以如果要输入带空格的字符串那么就应该这样:
string str;
getline(cin,str);
cout<<str<<endl;

string字符串赋值

在这里插入图片描述

	//string 的赋值操作;


	//直接赋值
	s1 = s2;
	cout << s1 << endl;


	//字符指针赋值
	char* p1 = (char*)"hello";
	s2 = p1;
	cout << s2 << endl;


	//单字符赋值
	s3 = 'c';
	cout << s3 << endl;


	//const char类型的指针赋值
	s1.assign((const char*)p1);
	cout << s1 << endl;

	//赋值前三个字符
	s1.assign((const char*)p1, 3);
	cout << s1 << endl;

	//把s1赋值给s2
	s2.assign(s1);
	cout << s2 << endl;

	//赋值四个d给s1
	s1.assign(4, 'd');
	cout << s1 << endl;

字符串拼接
在这里插入图片描述


	cout << s1 + s2 << endl;
	cout << s1 + "helllo" << endl;
	cout << s1 + 'c' << endl;
	cout << s1.append(s1) << endl;
	cout << s1.append("hello") << endl;

	//前两个
	cout << s1.append("hellosss", 2) << endl;

	//字符串“hello”从pos开始的第n个字符赋值添加到s2的末尾
	cout << s2.append("hello", 0, 1) << endl;

string查找和替换


	string s1 = "zxcvbnmasdfghjklqwertyuiop";

	//从左边第2个位置开始找,这里不一定要是a,也可以是其他字符串,没有2则默认是0
	cout << s1.find("a", 2) << endl;


	//rfind从右边找,一般用于找最后一个


	//替换把2和3之间的替换成1111,整体替换,就算不足四个还是整体替换
	cout << s1.replace(2, 3, "1111");


算法里面也有find函数:find(a,a+10,3);返回的是一个迭代器

字符串比较

想等返回0;>返回1;<返回-1;


cout<<s1.compare("12345");


字符串存取


	cout << s1[3] << endl;
	cout << s1.at(3) << endl;

字符串插入删除


	cout << s1.insert(2, "hellos") << endl;
	//删除从pos开始的n个字符,注意了,不是删除0到4区间的值
	cout << s1.erase(0, 4) << endl;

下标都从0开始

截取字符串

在这里插入图片描述

	//返回从2开始的3个字符,一般用于截取字符串:s.substr(n, s.size() - n)
	cout << s1.substr(2, 3) << endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值