我们在C++的开发中经常会碰到string、char*以及CString,这三种都表示字符串类型,有很多相似又不同的地方,常常让人混淆。下面详细介绍这三者的区别、联系和转换:
各自的区别
char*:
char*是一个指向字符的指针,是一个内置类型。可以指向一个字符,也可以表示字符数组的首地址(首字符的地址)。我们更多的时候是用的它的第二的功能,来表示一个字符串,功能与字符串数组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】
[cpp] view plain copy 在CODE上查看代码片派生到我的代码片
#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.
相互的转换
既然这两种类型都可用于表示字符串,但又是不同的类型,那他们如何转换呢?可用的方法参见如下:
char*与string的转换
【例3】
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.
总结
从灵活度来说,string最灵活易用,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