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;
}
};
463

被折叠的 条评论
为什么被折叠?



