C++ 学习之string 字符串比较、存取、插入删除、求子串

1、字符串比较

比较函数原型:

  • int compare(const string &s) const; //与字符串s比较
  • int compare(const char *s) const; //与字符串s比较

比较方式:

  • 字符串比较是按字符的ASCII码进行对比
= 返回   0

> 返回   1 

< 返回  -1

总结:字符串对比主要是用于比较两个字符串是否相等,判断谁大谁小的意义并不是很大

2、字符串存取

string中单个字符存取方式有两种

  • char& operator[](int n); //通过[]方式取字符
  • char& at(int n); //通过at方法获取字符

总结:string字符串中单个字符存取有两种方式,利用 [ ] 或 at

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;


//字符串比较是按字符的ASCII码进行对比

void test01()//字符串大小比较
{
	string str1("hello");
	string str2("xello");

	int ret = str2.compare(str1);
	if (ret == 0)
	{
		cout << "两个字符串相等" << endl;
	}
	if (ret == 1)
	{
		cout << "str2大于str1" << endl;
	}
	if (ret == -1)
	{
		cout << "str2小于str1" << endl;
	}
}


void test02()//字符串存取
{
	string str;
	str = "12345678";

	cout << str.size() << endl;

	for (int i = 0; i < str.size(); i++)//[ ]方式读取
	{
		cout << str[i] << " ";
	}


	for (int i = 0; i < str.size(); i++)//at方式读取
	{
		cout << str.at(i) << " ";
	}

	str[7] = 'x';
	str.at(0) = 'x';

	cout << str << endl;

}

int main()
{
	test01();
	test02();
	return 0;
}
3、字符串插入和删除

函数原型:

  • string& insert(int pos, const char* s); //插入字符串
  • string& insert(int pos, const string& str); //插入字符串
  • string& insert(int pos, int n, char c); //在指定位置插入n个字符c
  • string& erase(int pos, int n = npos); //删除从Pos开始的n个字符

总结:插入和删除的起始下标都是从0开始

4、求子串,字符串截取

函数原型:

  • string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串

总结:灵活的运用求子串功能,可以在实际开发中获取有效的信息

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


void test01()//插入删除字符
{
	string str1 = "hello";//定义的同时可以赋值字符串

	str1.insert(1, "123");//从第一个位置起,插入字符串   最后变成h123ello;

	cout << str1 << endl;

	str1.erase(1, 3);//从第一个位置起删除三个字符

	cout << str1 << endl;

}


void test02()//求子串
{
	string s1 = "hello";
	string s2 = s1.substr(1, 3);//从s1的第一个位置,取三个字符

	cout << s2 << endl;//ell
	
}

void test03()//求子串的实用操作
{
	string s1 = "xcl@1234567.com";//截取出用户名字

	int pos = s1.find('@');//首先找到@的位置

	string usr_name = s1.substr(0, pos);//从第0个位置开始,取到@之前

	cout << usr_name << endl;

	
}


int main()
{
	
	//string s1 = 'a';//错误,不能定义的同时不能赋值一个字符
	string s2;
	s2 = 'a';

	//test01();

	//test02();


	test03();

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值