首页 > 其他分享 >【标准库中的string类】

【标准库中的string类】

时间:2024-10-14 18:22:19浏览次数:3  
标签:string int s1 库中 标准 str main cout

【知识预告】

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

标签:string,int,s1,库中,标准,str,main,cout
From: https://blog.csdn.net/double__main__/article/details/142911153

相关文章

  • wms智能仓储管理系统标准化流程
    wms智能仓储管理系统标准化流程的标准化流程通常包括以下几个主要步骤: 需求分析:与客户充分沟通,了解其仓储管理需求和业务流程,确定系统功能和特性的需求,制定系统开发和实施计划。系统设计:根据需求分析结果,设计WMS系统的功能模块、流程和界面,包括入库管理、出库管理、库存管理......
  • STL——string类的模拟实现
    一.STL简介 1.1什么是STL STL(standardtemplatelibaray-标准模板库):是C++标准库的重要组成部分,不仅是一个可复用的组件库,而且是一个包罗数据结构与算法的软件框架。1.2STL的六大组件接下来开始模拟实现STL中的常用string类三个成员变量char*......
  • TIM定时器(标准库)
    目录一.前言二.定时器的框图三.定时中断的基本结构 四.TIM定时器相关代码五.最终现象展示一.前言    什么是定时器?定时器可以对输入的时钟进行计数,并在计数值达到设定值时触发中断。TIM定时器不仅具备基本的定时中断功能,而且还包含内外时钟源选择,输......
  • StringUtils Java字符串工具类
    在我们的代码中经常需要对字符串判空,截取字符串、转换大小写、分隔字符串、比较字符串、拼接字符串、使用正则表达式等等。如果只用String类提供的那些方法,我们需要手写大量的额外代码,不然容易出现各种异常。现在有个好消息是:org.apache.commons.lang3包下的StringUtils工......
  • Java【String类】
    字符串的本质是字符数组,是由字母、数字、汉字、下划线组成的一串字符。在Java中字符串属于对象。字符串是常量,内容用双引号括起来,在创建之后不能更改,但是可以使用其他变量重新赋值的方法进行更改。目录1.String类创建方式1.1直接创建1.2用new关键字创建2.String类的A......
  • 未发表的原创模型!三类典型需求响应负荷的标准化建模+共享储能提升灵活性(Matlab代码实
      ......
  • #STM32#定时器扫描按键消抖#按键控制LED灯亮灭#标准库
    一.机械按键抖动在按下按键后金属弹片会来回震动影响I/O口的电平变化,影响检测和判断操作。通常抖动时间为:5ms~10ms影响:在不加消除抖动的情况下按下按键LED灯可能会出现失灵的情况,因为这时的判断按键情况通常是判断电平的高低,由于电平不停的发转,所以呀很难判断此时是否是被......
  • 三维无限深势阱的标准解
    一、问题描述考虑一个粒子被限制在三维无限深方势阱中,势阱在三个方向上的边界分别为:\(0\leqx\leqL_x\)\(0\leqy\leqL_y\)\(0\leqz\leqL_z\)在势阱内部(即\(0\leqx\leqL_x\)、\(0\leqy\leqL_y\)、\(0\leqz\leqL_z\)),势能\(V=0\);而在势阱外部,势能......
  • 【转载】scipy.stats.norm.ppf —— 分位点函数(CDF的逆)(也被用作“标准偏差乘数”)
    原文地址:https://www.cnblogs.com/jiangkejie/p/15292260.htmlscipy.stats.norm.ppf()分位点函数(CDF的逆)(也被用作“标准偏差乘数”)即累计分布函数的逆函数(分位点函数,给出分位点返回对应的x值)。scipy.stats.norm.ppf(0.95,loc=0,scale=1)返回累积分布函数中概率等于0.95对应......
  • 【标准系列】国家标准平台
    前言标准是对重复性十五和概念所做的统一规定,它以科学技术和实践经验的结合成果为基础,经有关方面协商一致,由主管机构批准,以特定形式发布作为共同遵守的准则和依据。国家标准全文公开系统该系统收录现行有效强制性国家标准2049项。其中非采标1,451项可在线阅读和下载,采标598项......