栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ string、vector<char>和(const)char *之间的转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ string、vector<char>和(const)char *之间的转换

写C++程序时经常会遇到string、vector和(const)char *之间的转换,本文介绍了其间的转换方法和注意事项。

1. string转vector

string所存储字符串不包含'',所以转为vector后,通过vector.data()直接输出会有问题,会往后找直到'',会出现乱码。所以应该在vector后手动再加上'',这样在vector.data()输出字符串就没问题了。但此时vector.size()会比string.length()多1(结束符)。

#include 
#include 
#include 

using namespace std;

int main(void)
{
	string str = "Hello world";
	cout<<"str: length="< vec0(str.begin(), str.end());  
	//vec0.emplace_back('');
	cout<<"vec0: size="< vec1;
    
    //先定义vector, 再通过assign()利用string初始化	
	vec1.assign(str.begin(), str.end());  
	//vec1.emplace_back('');
	cout<<"vec1: size="< vec2(str.data(), str.data()+str.length());	
	//vec2.emplace_back('');
	cout<<"vec2: size="<#include 
#include 
#include 

using namespace std;
int main(void)
{
	const char *buf = "Hello world";
	cout<<"str: length="<的同时初始化
	vector vec1(buf, buf+strlen(buf));
	vec1.emplace_back('');
	cout<<"vec1: size="<, 后通过assign()填充数据
	vector vec2;
	vec2.assign(buf, buf+strlen(buf));
	vec2.emplace_back('');
	cout<<"vec2: size="<#include 
#include 
#include 
#include 

using namespace std;
int main(void)
{
	const char *buf = "Hello world";
	vector vec1(buf, buf+strlen(buf));
	//vector最后没有存入'',但是创建string时指定了size,就不会有问题
	string str1(vec1.data(), vec1.size()); 
	cout<<"str1: size="< vec2(buf, buf+strlen(buf));
	vec2.emplace_back('');
	string str2(vec2.data()); 
	cout<<"str2: size="<#include 
#include 
#include 
#include 

using namespace std;
int main(void)
{
	const char *buf = "Hello world";
	string str = buf;
	cout<<"str:"<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001001.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号