CStringとstring、char*の違いと変換


私たちはC++の開発でstring、char*、CStringによく遭遇します.この3つは文字列のタイプを表し、似ているところや違うところが多く、よく混同されます.この3つの違い、連絡、変換について詳しく説明します.
それぞれの違い
char*:
char*は文字を指すポインタで、内蔵タイプです.1文字を指すことも、文字配列の先頭アドレス(先頭文字のアドレス)を表すこともできます.より多くの場合、文字列を表す2番目の機能を使用します.機能は文字列配列char ch[n]と同じで、文字列を表すとき、最後に文字列の終了フラグとして'0'の終了記号があります.
【例1】
#include <iostream>
using namespace std;
void testCharArray()
{
	char ch1[12] = "Hello Wrold"; //    ch1[12],ch1[11]     ,  array bounds overflow
	char *pch1 , *pch2 = "string";
	char *pch3, *pch4;
	pch3 = &ch1[2];	//ch1[2]     pch3
	char ch = 'c';
	pch4 = &ch;
	pch1= ch1;
	cout << ch1 << endl;	//  ch1[0] \0       
	cout << pch1 << endl;	//  ch1[0] \0       
	cout << pch2 << endl;	//  ch1[0] \0       
	cout << pch3 << endl;	//  ch1[2] \0       
	cout << *pch3 << endl;	//   pch3  pch3     
	cout << *pch4 << endl;	//   pch4  pch4     
}

結果:
Hello Wrold
Hello Wrold
string
llo Wrold
l
C
 
string:
stringはC++標準ライブラリ(STL)のタイプで、ヘッダファイルに定義されたクラスです.文字列に対する様々な一般的な操作が含まれており、char*よりもコンテンツが動的に拡張され、文字列の操作が便利で迅速で、+番号で文字列の接続を行うのが最も一般的な操作です.
【例2】
#include <string>
void testString()
{
	string s1 = "this";
	string s2 = string(" is");
	string s3, s4;
	s3 = string(" a").append("string.");
	s4 = s1 + s2 + s3;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s4.size() << endl;
	s4.insert(s4.end()-7, 1, ' ');
	cout << s4 << endl;
}

結果:
this
 is
 astring.
this is astring.
16
this is a string.
 
CString
CStringは、MFCプログラミングにおいてよく用いる、MFCに属するクラスであり、例えば、ダイアログボックスからGetWindowTextを利用して得る文字列がCStringタイプであり、CStringはヘッダファイルにあります.CString(typedef CStringT>CString)は、Visual C++で最も一般的な文字列クラスである、CSimpleStringTクラスから継承され、主にMFCやATLプログラミングに適用されるため、CStringを使用する場合はafxを含む.hファイル#include.
【例3】
#include <afx.h>
//  CString    C++      ,   <<       ,
//      cout<<cstr     ,           。
void printCString(const CString &cstr);
void testCString()
{
	char *ch = "Hello";
	string s = "Wrold";
	CString cstr1(ch), cstr2(s.c_str()), cstr3("Program");
	printCString(cstr1);
	printCString(cstr2);
	printCString(cstr3);
	CString cstr4, cstr5;
	cstr4 = cstr1 + cstr2 + cstr3;
	cstr5 = cstr1 + " " + cstr2 + " " + cstr3;
	printCString(cstr4);
	printCString(cstr5);
}

void printCString(const CString &cstr) 
{
	int n = cstr.GetLength();
	for(int i=0; i<n; i++)
	{
		printf("%c", cstr[i]);
	}
	printf("
"); }

結果:
Hello
Wrold
Program
HelloWroldProgram
Hello Wrold Program
 
CStringの使い方については、以下を参照してください.http://www.cnblogs.com/Caiqinghua/archive/2009/02/16/1391190.html
 
CStringの使用中に発生する可能性のあるエラー:
 
コンパイル中に次のようなエラーが発生します.
    Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d] C:\Program Files (x86)\Microsoft Visual Studio 8\VC\ce\atlmfc\include\AFX.h 24
解決方法:
(注:私が使っている開発環境はVS 2010で、他のVSの環境類似操作です)
方法1:ここでエラーメッセージは欠落を意味する_AFXDLLというマクロなので、Project——>propertyでは、C/C++の中にPreprocessor(プリコンパイル)が入っています.AFXDLLというマクロ、OKできました!!
方法2:あなたのアイテムを右クリックして、「プロパティ」、「設定プロパティ」、「通常」の順に選択し、右側に「アイテムデフォルト」があり、下にMFCの使用があり、「共有DLLでMFCを使用」を選択すればOK~~
参考記事:http://blog.csdn.net/ahjxly/article/details/8465209
                         http://blog.csdn.net/zhoxier/article/details/7929920
 
char*,stringおよびCStringの関係を説明すると,このいくつかのヘッダファイルはまたぼんやりしていて、紙幅の原因で、この部分の内容は次の節で説明して、歓迎して読みます:《の違い》
 
そうごへんかん
この3つのタイプが文字列を表すのに使用できるが、異なるタイプである以上、どのように変換しますか?使用可能な方法は次のとおりです.
char*とstringの変換
【例4】
void pCharToString()
{
	//from char* to string
	char * ch = "hello world";
	string s1 = ch;	//        
	string s2(ch), s3;
	s3 = string(ch);
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	//from string to char*
	string str = string("string is commonly used.");
	/*************************************************************************
	          string   char*,  string             ,
	            , str[1]   1   't'
	**************************************************************************/
	const char *ch1 = str.c_str();	
	cout << ch1 << endl;
}

結果:
hello world
hello world
hello world
string is commonly used.
char*とCString
【例5】
void pCharToCString()
{
	//from char* to CString
	char *ch = "char pointer.";
	CString cStr1 = ch;
	CString cStr2 = CString(ch);
	printCString(cStr1);
	printCString(cStr2);
	//from CString to char*
	CString cstr = "CString";
	char* chs=cstr.getbuffer(0);//    VS2010      ,   【 6】
	cout << chs << endl;
}

結果:
char pointer.
char pointer.
CString
stringとCString
【例6】
void stringToCString()
{
	//from string to CString
	string s1 = "string1 to CString";
	string s2 = "string2 to CString";
	string s3 = "string3 to CString";
	CString cstr(s1.c_str());
	printCString(cstr);
	CString cstr2;
	cstr2.Format("%s", s2.c_str());	// string to CString
	printCString(cstr2);
	cstr2.Format("%s", s3.data());	// string to CString
	printCString(cstr2);

	//from CString to string
	CString cstr3 = "CString to string3";
	CString cstr4 = "CString to string4";
	string str;
	str=cstr3.GetBuffer(0);
	cout << str << endl;
	str = LPCSTR(cstr4); 
	cout << str << endl;
}

結果:
string1 to CString
string2 to CString
string3 to CString
CString to string3
CString to string4
c_str()とdata()の違いは、前者は′/0′付きの文字列を返し、後者は′/0′なしの文字列を返す.
VS 2010環境では、cstr 2.Format("%s", s2.c_str());cstr2.Format("%s", s3.data());及びstr=cstr 3.GetBuffer(0);str = LPCSTR(cstr4); 編集できるかもしれませんが、error C 2664:'void ATL::CStringT::Format(const wchar_t*,...):cannot convert parameter 1 from 'const char [3]' to 'const wchar_t*'のエラー.これは、あなたのプロジェクトの文字セットがマルチバイト文字セットではないためです.あなたのプロジェクト属性をマルチバイト文字セットに設定すればいいです.方法は、プロジェクトを右クリックし、PropertiesConfigurations PropertiesGeneralを選択し、右側のProject Defaultsの下のCharacter SetでUse Multi-Byte Character Setを選択します.
まとめ
柔軟性から言えばstringが最も使いやすく、次いでCStringでchar*の拡張性と柔軟性が悪い.一般的に標準ベースのライブラリ開発ではstring,MFCやATLプログラミングではCStringを用いる.
CString、string間の変換には他の方向もありますが、基本的にはchar*を橋渡しとしています.char*はstringに簡単に変換することができ、CStringに簡単に変換することができるからです.
 
もっとCStringの使い方も以下のリンクを参考にすることができます.彼らがもっと詳しく書いたので、私はもう繰り返しません.
http://www.cnblogs.com/Caiqinghua/archive/2009/02/16/1391190.html
http://blog.csdn.net/lewutian/article/details/6787024
「C/C++夢のチーム」学習グループへようこそ:226157456