將 char * 或者 char 轉換為 string——直接賦值即可轉換。
將string轉換為char * 或者char 。
string 是c++標準庫裡面其中乙個,封裝了對字串的操作
把string轉換為char* 有3種方法:data()/c_str()/copy().
1.呼叫 string的data()函式
(1)以字元陣列的形式返回字串內容,但並不新增'\0'。
(2)data()方法掉用後返回的是乙個const char*型別的指標。
(3)const char*型別預設是無法自動轉換成char*型別的。強制如下char* p2 = const_cast(p1);
2. 呼叫string的c_str()函式
(1)返回乙個以'\0'結尾的字元陣列。
(2)c_str()方法掉用後返回的也是乙個const char*型別的指標。
(3)const char*型別預設是無法自動轉換成char*型別的。強制如下char* p2 = const_cast(p1);
#include#include using namespace std;
int main(){
/*首先是char*或者char轉換為string*/
const char* ch1="hello";//沒有const會抱乙個警告
char ch2="world";
string str1=ch1;
cout
cout
cout執行結果如下:
補充:關於c_str()必須要說明的一點是這個陣列的資料是臨時的,當有乙個改變這些資料的成員函式被呼叫或者原先那個str變數的內容改變之後c_str()轉換得到的const char*指標所指向的資料也會發生改變。因此要麼現用現轉換,要麼把它的資料複製到使用者自己可以管理的記憶體中後再轉換。看下面這個例子演示上述情況。
//演示問題的程式示例
#include#include using namespace std;
int main(){
string str="hello,world!";
const char* cstr=str.c_str();
cout
int main(){
char* cstr=new char[20];
string str="hello,world!";
strncpy(cstr,str.c_str(),str.size());
cout兩個程式的執行結果分別如下:
先寫這一些,,吃個飯有空在過來補充。參考這篇
3. 呼叫 string的copy 函式
(1)形式:str.copy(p,n,startindex=0)。其中:
p為目的位址的指標,n為複製的字元數,startindex為拷貝起始的位置;返回值是實際拷貝的字元個數。
(2)c++字串並不以'\0'結尾。
(3)有使用者來確保p所指向的空間足夠來儲存n個字元。
#include#include using namespace std;
int main(){
string str="hello,world!";
const char* cstr=str.c_str();
cout執行結果如下:
c 數字與字串的相互轉換
首先推薦用用c 的stringstream。主要原因是操作簡單。數字轉字串,int float型別 同理 include include int main 字串轉數字,int float型別 同理 int main 上面方法的優點就是使用簡單方便,確定可能會相對別的方法來說慢一點,但是一般少量的資料...
c 數字與字串的相互轉換
首先推薦用用c 的stringstream。主要原因是操作簡單。數字轉字串,int float型別 同理 include include int main 字串轉數字,int float型別 同理 int main 上面方法的優點就是使用簡單方便,確定可能會相對別的方法來說慢一點,但是一般少量的資料...
c 數字與字串的相互轉換
首先推薦用用c 的stringstream。主要原因是操作簡單。0x00 字串轉數字 zcj 14.cpp 該程式是乙個序號產生器,原理是對輸入的字元每個與2求異或的結果取低位即為序號產生器。先輸入乙個字元陣列在轉化的int陣列再逐個與2求異或後儲存 include pch.h include in...