【C++标准库中的string类】

【知识预告】

  1. string类的常用接口说明
  2. string类对象的访问及遍历操作
  3. string类对象的容量操作
  4. string类对象的修改操作
  5. 相关例题

1 string类的常用接口说明(只写了常用的)

千言万语都不如来段代码直接

int main()
{
	string s1;
	string s2("hello");

	cin >> s1;
	cout << s1 << endl;
	cout << s2;

	// char str[1600];
	// 静态数组没办法很好的按需分配空间
	// 比scanf强太多了

	string ret1 = s1 + s2;
	cout << ret1 << endl;

	string ret2 = s1 + "我来了";
	cout << ret2 << endl;
	return 0;
}

2 string类对象的访问及遍历操作

2.1 for循环遍历

int main()
{
	string s1("hello world");
	string s2 = "hello world";

	// 遍历string
	for (size_t i = 0; i < s1.size(); i++)
	{
		// 读
		cout << s1[i] << " ";
	}
	
	cout << endl;
	
	for (size_t i = 0; i < s1.size(); i++)
	{
		// 写
		s1[i]++;
	}
	
	cout << s1 << endl;
	return 0;
}

2.2 迭代器遍历

int main()
{
	string s1("hello world");
	
	// 迭代器,都是定义在类域里面
	string::iterator it = s1.begin();
	
	//while (it < s1.end())  这里可以用,但是不建议
	while (it != s1.end())  // 推荐使用!=,通用
	{
		// 读
		cout << *it << " ";  // it类似指针
		it++;
	}
	cout << endl;

	it = s1.begin();
	while (it != s1.end())
	{
		// 写
		*it = 'a';
		it++;
	}
	cout << endl;
	cout << s1 << endl;
	
	return 0;
}

2.3 范围for遍历

int main()
{
	string s1("hello world");
	
	// 读
	for (auto ch : s1)  // 范围for
	{
		cout << ch << " ";
	}
	cout << endl;

	// 写
	for (auto& ch : s1)
	{
		ch++;
	}
	cout << endl;
	cout << s1 << endl;

	return 0;
}
void func(const string& s)
{
	//string::const_iterator it = s.begin();
	auto it = s.begin();

	while (it != s.end())
	{
		// const迭代器,只能读不能写
		cout << *it << " ";
		it++;
	}
	cout << endl;

	//string::const_reverse_iterator rit = s.rbegin();
	auto rit = s.rbegin();   // auto可以简化

	while (rit != s.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;
}

int main()
{
	string s1("hello worldxxxxxxxx");
	func(s1);

	string s2(s1);
	cout << s2 << endl;  // hello worldxxxxxxxx

	string s3(s1, 6, 5);
	cout << s3 << endl;  // world

	string s4(s1, 6, 3);
	cout << s4 << endl;  // wor

	string s5(s1, 6);   // worldxxxxxxxx
	cout << s5 << endl;

	string s6(s1, 6, s1.size() - 6);
	cout << s6 << endl;  // worldxxxxxxxx

	string s7(10, 'a');
	cout << s7 << endl;   // aaaaaaaaaa

	string s8(++s7.begin(), --s7.end());
	cout << s8 << endl;   // aaaaaaaa

	s8 = s7;
	cout << s8 << endl;  // aaaaaaaaaa
	s8 = "xxx";
	cout << s8 << endl;   //  xxx
	s8 = "y";
	cout << s8 << endl;   // y

	return 0;
}

3 string类对象的容量操作

int main()
{
	string s1("hello world");
	cout << s1.size() << endl;     // 11
	cout << s1.length() << endl;   // 11
	cout << s1.capacity() << endl; // 15

	s1.clear();
	s1 += "张三";
	cout << s1.size() << endl;   // 4
	cout << s1.capacity() << endl;  // 15

	cout << s1.max_size() << endl; // 2147483647,这个用的少

	return 0;
}
int main()
{
	string s;
	s.reserve(100);  // 保留100个空间

	size_t old = s.capacity();
	cout << "初始:" << s.capacity() << endl;
	// 初始:111  一般VS会多开一点空间

	for (size_t i = 0; i < 100; i++)
	{
		s.push_back('x');

		if (s.capacity() != old)
		{
			cout << "扩容:" << s.capacity() << endl;
			old = s.capacity();
		}
	}
	cout << s << endl;   // 打印100个x

	s.reserve(10);  // 可以开空间,但一般不缩小
	cout << s.capacity() << endl;   // 111

	return 0;
}
int main()
{
	string s1("hello world");
	cout << s1 << endl;              // hello world
	cout << s1.size() << endl;       // 11
	cout << s1.capacity() << endl;   // 15

	s1.resize(13);
	// 打印的时候看不出来变化,后面补了\0
	cout << s1 << endl;              // hello world
	cout << s1.size() << endl;       // 13
	cout << s1.capacity() << endl;   // 15
	return 0;
}
int main()
{
	string s1("hello world");
	s1.resize(13, 'x');   // 在已有的数据上再插入数据
	cout << s1 << endl;              // hello worldxx
	cout << s1.size() << endl;       // 13
	cout << s1.capacity() << endl;   // 15

	s1.resize(20, 'x');
	cout << s1 << endl;              // hello worldxxxxxxxxx
	cout << s1.size() << endl;       // 20
	cout << s1.capacity() << endl;   // 31

	s1.resize(5);   // 保留前5个字符
	cout << s1 << endl;              // hello
	cout << s1.size() << endl;       // 5
	cout << s1.capacity() << endl;   // 31

	string s2;
	s2.resize(10, '#');
	cout << s2 << endl;              // ##########
	cout << s2.size() << endl;       // 10
	cout << s2.capacity() << endl;   // 15

	s2[0]++;
	s2.at(0)++;                     // 这个用的少
	cout << s2 << endl;             // %#########

	return 0;
}

插入点文字总结一下:

  1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
  2. clear()只是将string中有效字符清空,不改变底层空间大小。
  3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变

4 string类对象的修改操作

int main()
{
	string ss("world");
	string s;
	s.push_back('#');
	s.append("hello ");
	s.append(ss);
	cout << s << endl;  // #hello world

	s += '#';
	s += "hello ";
	s += ss;
	cout << s << endl; // #hello world#hello world

	string ret1 = ss + '#';
	string ret2 = ss + "hello ";
	cout << ret1 << endl;    // world#
	cout << ret2 << endl;    // worldhello
	
	return 0;
}
int main()
{
	string str("xxxxxxxxxx");
	string base = "The quick brown for jumps over a laze dog.";

	str.assign(base);   // assign平时用的很少
	cout << str << endl;  // The quick brown for jumps over a laze dog.

	str.assign(base, 5, 10);
	cout << str << endl; // uick brown
	
	return 0;
}
int main()
{
	// insert和erase能不用就不用
	// 它们都设计挪动数据,效率低
	string str("hello world");
	str.insert(0, 2, 'x');
	//str.insert(str.begin(), 'x'); // xhello world
	cout << str << endl;            // xxhello world

	str.erase(5);
	cout << str << endl;  // xxhel

	// replace接口设计复杂繁多,也不建议用
	string s1("hello world");
	s1.replace(5, 1, "%");
	cout << s1 << endl;  // hello%world

	// 将空格替换为20%
	string s2("The quick brown for jumps over a laze dog.");
	string s3;
	for (auto ch : s2)
	{
		if (ch != ' ')
		{
			s3 += ch;
		}
		else
		{
			s3 += "20%";
		}
	}
	cout << s2 << endl;  // The quick brown for jumps over a laze dog.
	cout << s3 << endl; // The20%quick20%brown20%for20%jumps20%over20%a20%laze20%dog.

	// 如果我想把s3的数据给s2
	//s2 = s3;
	//s2.assign(s3);
	//swap(s2, s3);
	s2.swap(s3);
	cout << s2 << endl;
	
	return 0;
}
int main()
{
	string s1("test.cpp");
	size_t i = s1.find('.'); // 找.所在的位置赋值给i
	cout << i << endl;  // 4
	string s2 = s1.substr(i); // 把i和i后面位置的字符串赋值给s2
	cout << s2 << endl;  // .cpp
	
	return 0;
}
int main()
{
	string s1("test.cpp.tar.zip");
	size_t i = s1.rfind('.'); // 倒着找. 把.的位置赋值给i
	cout << i << endl;  // 12

	string s2 = s1.substr(i); // 把i位置后面的字符串赋值给s2
	cout << s2 << endl;  // .zip

	string s3("https://legacy.cplusplus.com/reference/string/string/rfind/");
	// 协议:https  协议不一定都是https还可能是http等其它协议
	// 域名:legacy.cplusplus.com   不一定都是com结尾,还可能是.edu/.cn
	// 资源名:reference/string/string/rfind/

	string sub1, sub2, sub3;
	size_t i1 = s3.find(':');  // 查文档可知,如果没找到: 会返回npos
	if (i1 != string::npos)
		sub1 = s3.substr(0, i1);  // 左闭右开,不包含:
	else
		cout << "没有找到i1" << endl;

	size_t i2 = s3.find('/', i1 + 3);
	if (i2 != string::npos)
		sub2 = s3.substr(i1 + 3, i2 - (i1 + 3));  // 第一个参数是起始位置
	else                                          // 第二个参数表示起始位置往后多少个字符停止
		cout << "没有找到i2" << endl;

	sub3 = s3.substr(i2 + 1);

	cout << sub1 << endl;  // https
	cout << sub2 << endl;  // legacy.cplusplus.com
	cout << sub3 << endl;  // reference/string/string/rfind/
	
	return 0;
}
int main()
{
	string str("Please, replace the vowels in this sentence by asterisks.");
	size_t found = str.find_first_of("aeiou");

	while (found != string::npos)
	{
		str[found] = '*';
		found = str.find_first_of("aeiou", found + 1);
	}
	cout << str << endl;
	// Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
	
	return 0;
}

常用的语法介绍完了,现在做几个题目:
1、LeetCode 917 仅仅反转字母

class Solution {
public:

    bool isLetter(char ch)
    {
        if (ch >= 'a' && ch <= 'z')
            return true;
        if (ch >= 'A' && ch <= 'Z')
            return true;
        return false;
    }

    string reverseOnlyLetters(string s) {
        int begin = 0, end = s.size()-1;
        while(begin < end)
        {
            while (begin < end && !isLetter(s[begin]))
            {
                ++begin;
            }

            while (begin < end && !isLetter(s[end]))
            {
                --end;
            }

            swap(s[begin], s[end]);
            ++begin;
            --end;
        }
        return s;
    }
};

2、牛客网-字符串里面最后一个单词的长度

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

int main() 
{
    string str;
    // cin >> str;
    getline(cin,str);

    size_t i = str.rfind(' ');
    if (i != string::npos)
    {
        cout << str.size() -i - 1 << endl;
    }
    else
    {
        cout << str.size() << endl;
    }
    return 0;
}

插入一个getline的小用法

int main()
{
	//string s1, s2;
	//cin >> s1 >> s2;
	//cout << s1 << endl;
	//cout << s2 << endl;
	// cin是以换行或空格作为分隔符

	string str;
	// cin >> str;
	//getline(cin, str);     // 默认以换行作为分隔符
	getline(cin, str, '!');  // 以!作为分隔符
	// getline(cin, str, '\n');  // 以换行作为分隔符
	cout << str;
	return 0;
}

3、字符串相加

class Solution {
public:
    string addStrings(string num1, string num2) {

        int end1 = num1.size()-1, end2 = num2.size()-1;
        string str;
        
        // 进位
        int next = 0;
        while (end1 >=0 || end2 >=0)
        {
            int x1 = end1 >= 0 ? num1[end1] - '0' : 0;
            int x2 = end2 >= 0 ? num2[end2] - '0' : 0;
            int ret = x1 + x2 + next;
            
            // 进位
            next = ret / 10;
            ret = ret % 10;

            // 头插
            // str.insert(0,1,'0'+ret);   // 时间复杂度是O(N^2)

            // 尾插
            str += ('0'+ret);

            --end1;
            --end2;
        }
        if (next == 1)
        {
            // str.insert(0,1,'1');
            str += '1';
        }

        // 逆置
        reverse(str.begin(), str.end());  // 时间复杂度是O(N)
        return str;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值