Convert a std::string to char* in C++ - Techie Delight
文章推薦指數: 80 %
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
延伸文章資訊
- 1How to convert/parse from String to char in java?
If you want to parse a String to a char, whereas the String object represent more than one charac...
- 2Convert string to char array in C++ - GeeksforGeeks
A way to do this is to copy the contents of the string to char array. This can be done with the h...
- 3Convert a std::string to char* in C++ - Techie Delight
This post will discuss how to convert a `std::string` to `char*` in C++. The returned array shoul...
- 4Java Convert String to char - javatpoint
- 5String to char array java - convert string to char - JournalDev
char[] toCharArray() : This method converts string to character array. · char charAt(int index) :...