Convert a std::string to char* in C++ - Techie Delight

文章推薦指數: 80 %
投票人數:10人

This post will discuss how to convert a `std::string` to `char*` in C++. The returned array should contain the same sequence of characters as present in the ... Skiptocontent Thispostwilldiscusshowtoconvertastd::stringtochar*inC++.Thereturnedarrayshouldcontainthesamesequenceofcharactersaspresentinthestringobject,followedbyaterminatingnullcharacter(‘\0’)attheend. 1.Usingconst_castOperator Weknowthatbothstring::c_strorstring::datafunctionsreturnsconstchar*.Togetanon-constversion,wecanusetheconst_castoperator,whichremovestheconstattributefromaclass.Thisworksinconstanttimeasnocopyingisinvolved. Pleasenotethatthisapproachwillgiveusdirectaccesstotheunderlyingdatastructure(i.e.,anarray)behindstd::string.Thatmeansanychangetothechar*willbereflectedinthestringobjectandviceversa. 123456789101112 #include#include intmain(){    std::stringstr="std::stringtochar*";     char*c=const_cast(str.c_str());    std::cout<#include#include intmain(){    std::stringstr="std::stringtochar*";     char*c=strcpy(newchar[str.length()+1],str.c_str());    std::cout<#include intmain(){    std::stringstr="std::stringtochar*";    intlen=str.size();     char*c=newchar[len+1];    std::copy(str.begin(),str.end(),c);    c[len]='\0';     std::cout<#include#include intmain(){    std::stringstr="std::stringtochar*";     std::vectorchars(str.begin(),str.end());    chars.push_back('\0');     char*c=&chars[0];    std::cout<#include intmain(){    std::stringstr="std::stringtochar*";     char*c=&*str.begin();    std::cout<



請為這篇文章評分?