1. 程式人生 > >String與C風格字串轉換

String與C風格字串轉換

String字串轉換為C風格字串需要利用string類的成員函式c_str()。而C風格字串轉換轉換為string字串可以直接利用運算子=。首先介紹c_str()函式原型:

const value_type *c_str() const;

它的返回值型別為const char*,所以定義的C風格字串需要用const char*指標指向,變數名為ch。string型別變數為str,值為hello,ch指向的字串內容為world。程式碼實現如下:

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str="hello";
	const char *ch;
	ch=str.c_str();
	cout<<ch<<endl;

	ch="world";
	str=ch;
	cout<<str<<endl;
return 0;
}