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 会完整读取包括空格在内的所有字符,直到遇到分隔符(默认换行),适合读取整行输入。

相关推荐
Alice-YUE5 小时前
【js高频八股】防抖与节流
开发语言·前端·javascript·笔记·学习·ecmascript
云泽8085 小时前
C++11 核心特性全解:列表初始化、右值引用与移动语义实战
开发语言·c++
froginwe115 小时前
DOM 加载函数
开发语言
Hello eveybody5 小时前
介绍一下背包DP(Python)
开发语言·python·动态规划·dp·背包dp
AI进化营-智能译站5 小时前
ROS2 C++开发系列12-用多态与虚函数构建可扩展的ROS2机器人行为模块
开发语言·c++·ai·机器人
iCxhust6 小时前
微机原理实践教程(C语言篇)---A002流水灯
c语言·开发语言·单片机·嵌入式硬件·51单片机·课程设计·微机原理
Morwit6 小时前
QML组件之间的通信方案(暴露子组件)
c++·qt·职场和发展
qeen876 小时前
【数据结构】建堆的时间复杂度讨论与TOP-K问题
c语言·数据结构·c++·学习·
莎士比亚的文学花园6 小时前
Linux驱动开发(3)——设备树
开发语言·javascript·ecmascript
图码6 小时前
如何用多种方法判断字符串是否为回文?
开发语言·数据结构·c++·算法·阿里云·线性回归·数字雕刻