C++11:string类的常用接口说明及其功能测试

本文详细介绍了C++11中string类的常用接口,包括构造、容器操作、访问与遍历、修改等,并通过示例代码进行功能测试,如预留空间、追加字符、调整大小、遍历输出等。测试结果展示了string对象在不同操作下的状态变化。
摘要由CSDN通过智能技术生成

C++11:string类的常用接口说明及其功能测试

  1. string类对象的常见构造
  2. string类对象的容器操作
  3. string类对象的访问及其遍历操作
  4. string类对象的修改操作

测试代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
#include<functional>
using namespace std;

void fun(int n)
{
	string str;
	str.reserve(100);//一次性预留空间,提升效率,减少扩容次数
	for (int i = 0; i < n; ++i)
	{
		cout << "capacity = " << str.capacity() << endl;
		str.push_back('a');
	}
}

int my_strlen(const char *str)
{
	int count = 0;
	while (*str++ != '\0')
	{
		count++;
	}
	return count;
}

int main()
{
	//字符串构造
	string str1;
	cout << "str1 = " << str1 << endl;
	string str2("zxcvbnm");
	cout << "str2 = " << str2 << endl;
	string str3(10, '#');
	cout << "str3 = " << str3 << endl;
	string str4(str3);
	cout << "str4 = " << str4 << endl;

	//功能测试
	cout << "size = " << str3.size() << endl;//求有效字符长度
	cout << "length = " << str3.length() << endl;//字符串特有计算有效字符长度
	cout << "capacity = " << str3.capacity() << endl;//字符串容量
	str3 += "sadasdasdasda";
	cout << "capacity = " << str3.capacity() << endl;//自动扩容
	str3.clear();
	cout << "size = " << str3.size() << endl;
	
	str2.resize(15, '+');//重新调整元素个数
	cout << "str2 = " << str2 << endl;
	cout << "length = " << str2.length() << endl;
	cout << "capacity = " << str2.capacity() << endl;
	str2.resize(3, '+');
	cout << "str2 = " << str2 << endl;

	str2.reserve(10);//调整预留容量
	cout << "capacity = " << str2.capacity() << endl;
	str2.reserve(100);
	cout << "capacity = " << str2.capacity() << endl;

	//fun(100);
	for (unsigned int i = 0; i < str2.size(); ++i)
	{
		cout << str2[i];
	}
	cout << endl;

	auto it = str2.begin();
	while (it != str2.end())
	{
		cout << *it;
		++it;
	}
	cout<<endl;

	for (const auto &e : str2)
		cout << e;
	cout << endl;

	auto rit = str2.rbegin();
	while (rit != str2.rend())
	{
		cout << *rit;
		++rit;
	}
	cout << endl;

	str2.push_back('H');//在字符串后插入字符
	str2.append("xht");//追加字符串
	str2 += "mad";
	cout << str2 << endl;
	//C str 找到对象内部的指针将其类型强转为c类型的指针
	cout << "str length = " << my_strlen(str2.c_str()) << endl;

	string str = "https://blog.csdn.net/qq_42613519";
	//size_t pos = str.find('b');
	//size_t pos = str.find("net");
	size_t pos = str.rfind('4');
	if (pos != string::npos)
		cout << "pos = " << pos << endl;
	else
		cout << "查找字符不存在" << endl;

	size_t start_pos = str.find('b');
	size_t end_pos = str.find('9');
	cout << "pos = " << end_pos << endl;
	string tmp_str = str.substr(start_pos, end_pos - start_pos + 1);//获取子串
	cout << tmp_str << endl;


	system("pause");
	return 0;
}

测试结果(部分)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值