How to convert a char array to a string?(如何将char数组转换为字符串?)
问题描述
使用字符串的c_str 函数然后执行strcpy 将C++ string 转换为char 数组非常简单.但是,如何做到相反呢?
Converting a C++ string to a char array is pretty straightorward using the c_str function of string and then doing strcpy. However, how to do the opposite?
我有一个 char 数组,例如: char arr[ ] = "This is a test"; 要转换回:string str = "这是一个测试.
I have a char array like: char arr[ ] = "This is a test"; to be converted back to:
string str = "This is a test.
推荐答案
string 类有一个构造函数,它接受一个以 NULL 结尾的 C 字符串:
The string class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
这篇关于如何将char数组转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将char数组转换为字符串?
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
