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

相关推荐
吃好睡好便好1 天前
用while循环语句求和
开发语言·学习·算法·matlab·信息可视化
TechWayfarer1 天前
查询IP所在地的3种方案:从API到离线库,风控场景怎么选?
开发语言·网络·python·网络协议·tcp/ip
摇滚侠1 天前
Java 零基础全套教程,集合框架,笔记 153-163
java·开发语言·笔记
程序员榴莲1 天前
Python 单例模式
开发语言·python·单例模式
L、2181 天前
CANN算子开发调试实战:从“Segmentation Fault“到定位根因的完整流程
java·开发语言
狗凯之家源码网1 天前
基于PHP的多语言跨境电商B2B2C商城系统技术解析
开发语言·php
比特森林探险记1 天前
go 语言中的context 解读和用法
开发语言·后端·golang
古城小栈1 天前
Rust 调用 C 语言库 实战指南(企业级)
c语言·开发语言·rust
吃好睡好便好1 天前
用for循环语句求和
开发语言·人工智能·学习·matlab·学习方法