C與C++中的字符數組char*和字符串string的相互轉化


1. 將字符數組char[]轉化為字符串string

char ch [] = “ABCDEFG”;
string str(ch);//也可string str = ch;
//或者
char ch [] = “ABCDEFG”;
string str;
str = ch;//在原有基礎上添加可以用str += ch;

2. 將字符串string轉化為字符數組char[]

char buf[10];
string str(“ABCDEFG”);
length = str.copy(buf, 9);
buf[length] = ‘\0’;
//或者(推薦)
char buf[10];
string str(“ABCDEFG”);
strcpy(buf, str.c_str());//strncpy(buf, str.c_str(), 10);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM