我是靠谱客的博主 冷酷毛巾,这篇文章主要介绍C风格字符串和C++string对象的相互转化,现在分享给大家,希望可以做个参考。

一、C风格的字符串转化为C++的string对象

C++中,string 类能够自动将C 风格的字符串转换成string 对象
 
复制代码
1
2
3
4
5
6
7
8
9
10
#include <iostream> #include <string> using namespace std; int main() { char str[] = "hello, world!"; //char str[] = "hello, world!"; string str2(str); //string str2 = str; cout << "C风格:" << str << endl; cout << "C++风格:" << str2 << endl; return 0; }

二、C++的string对象转化为C风格的字符串

string提供一个方法可以直接返回字符串的首指针地址,即string.c_str()。比如string str = "Hi !"转换为char*类型。

const char* mystr = str.c_str(),在这里注意要加上const,因为c_str()返回的是const char *类型

 

 

转载于:https://www.cnblogs.com/fuqia/p/9648370.html

最后

以上就是冷酷毛巾最近收集整理的关于C风格字符串和C++string对象的相互转化的全部内容,更多相关C风格字符串和C++string对象内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部