STL---string 基本的成员函数

//  STL(标准模板库)
//  ascall码表(美):值(内存中的二进制数值)——文字字符 {存在一一映射关系}

1、STL—string 基本的成员函数介绍

string类的构造函数

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

void test_string1()
{
	//string类的构造函数
	string s1;
	//string s2("hello");
	string s2 = "hello"; // 构造+拷贝构造 ->优化成 直接构造
	cout<< s1 <<endl;
	cout<< s2 <<endl;

	string s3(s2);
	cout<< s3 <<endl;

	/*cin >> s1 >> s2;
	cout<< s1 <<endl;
	cout<< s2  <<endl;*/
}

string类的赋值运算符重载

void test_string2()
{
	string s1;
	string s2 = "hello world!!!";

	//赋值
	s1 = s2; //拷贝赋值
	//后面两种不常用
	s1 = "xxxxx";
	s1 = 'y';

}

operator[] 遍历string

void test_string3()
{
	string s1("hello,world");
	cout<< s1[0] <<endl;   //s1[0] --> s1.operator[](0) --> char& operator[](size_t pos)  取到string的第pos个字符
	s1[0] = 'x';
	cout<< s1[0] <<endl;
	cout<< s1 <<endl;

	//要求遍历string,每个字符+1
	for (size_t i=0; i<s1.size(); ++i)  //这里的 s1.size() 返回的是字符串s1的长度
	{
		s1[i]++;
	}
	cout<< s1 <<endl;

	s1[15];
}

int main()
{
	test_string3();
	return 0;
}

2、练习题

//T1、仅仅反转字母
// 给你一个字符串s,根据下述规则反转字符串:(1)所有非英文字母保留在原有位置  (2)所有英文字母(大写或小写)位置反转
// 返回反转后的 s 。

class Solution
{
public:
	bool IsLetter(char ch)
	{
		if ((ch >= 'a' && ch <= 'z')
			|| (ch >= 'A' && ch <= 'Z'))
			return true;
		else
			return false;
	}

	string reverseOnlyLetters(string s)
	{
		size_t begin = 0, end = s.size() - 1;
		while (begin < end)
		{
			while (begin < end && !IsLetter(s[begin])) //begin<end ,防止字符串s都不是字母,一直 ++begin,造成越界。
				++begin;
			while (begin < end && !IsLetter(s[begin]))
				--end;

			//当begin 和 end 都是字母时,交换
			swap(s[begin], s[end]);
			++begin;
			--end;
		}
		return s;
	}
	
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值