C++ ---string类(三)

一、string operations

1、c_str

这个是c++标准库中std::string类的c_str()成员函数,是c++中c风格字符串与c++string对象互转的核心接口。核心作用是:把c++的std::string对象转化为c语言兼容的以空字符\0结尾的字符数组,用来兼容c风格的字符串操作,比如c标准库的strlen,strcmp,或者需要const char* 参数的c语言函数。

(1)兼容c语言函数

cpp 复制代码
//1、兼容c语言函数
std::string s = "hello";
size_t len = strlen(s.c_str());
std::cout << len << std::endl;
	

(2)与c风格字符串互转

cpp 复制代码
	const char* c_str = "world";
	std::string s(c_str);


	//string 转c风格字符串
	const char* c = s.c_str();
	
	cout << c << endl;

2、data

3、get _allocator

这个函数的作用是返回当前std::string对象关联的分配器对象的拷贝

4、find

cpp 复制代码
string findsuffix(const string& filename)
{
	size_t i = filename.find('.');
	if (i != string::npos)
	{
		return filename.substr(i);
	}
	else
	{
		return "";
	}
}
void test9()
{
	string filename1("test.cpp");
	string filename2("test.c");
	string filename3("test");
	cout << findsuffix(filename1) << endl;
	cout << findsuffix(filename2) << endl;
	cout << findsuffix(filename3) << endl;
}

5、substr

substr(起始下标,截取长度)

6、rfind

从字符串末尾往前找,返回最后一次出现的位置

cpp 复制代码
void test11()
{

	 
		string s = "hello world hello c++";

		// 找最后一个 "hello"
		size_t pos = s.rfind("hello");

		if (pos != string::npos) {
			cout << "位置:" << pos << endl;
		}
		else {
			cout << "没找到" << endl;
		}

		
	
}

7、getline

cin >> 会自动跳过空格、换行等空白符,遇到空白就停止读取;

getline 会完整读取包括空格在内的所有字符,直到遇到分隔符(默认换行),适合读取整行输入。

相关推荐
名字还没想好☜8 小时前
Python f-string 进阶:数字格式化、对齐填充、调试 = 号与嵌套表达式
开发语言·数据库·python·字符串格式化·f-string
·薯条大王8 小时前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
一壶浊酒..11 小时前
Scrape Webpack练习
开发语言·javascript·webpack
命运之光11 小时前
【C语言完整代码】就诊信息管理系统
java·c语言·开发语言
命运之光12 小时前
【C语言完整代码】图书管理系统:图书馆场景下的增删改查实战
c语言·开发语言
猿长大人12 小时前
C# | Serilog 新手入门
开发语言·c#·.net·log
hansang_IR13 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
东东最爱敲键盘13 小时前
day7.c++继承
c++
在世修行13 小时前
从零打造 C# 工业视觉检测系统(七):串口通信 SerialPort 封装与开发
开发语言·c#·modbus rtu·rs232/rs485
沫璃染墨14 小时前
《从零入门Linux系统篇(十五):系统工具篇·六——GDB调试器详解:从程序执行控制到高级调试技巧》
linux·运维·服务器·c语言·c++