开发手册 欢迎您!
软件开发者资料库

C++ 字符串

字符串是一种非常重要的数据类型,C++中有两种类型的字符串表示形式,分别是C 风格字符串和String 类字符串。本文主要介绍C++字符串。

1、C 风格字符串

C 风格字符串是使用\0终止的一维字符数组。'\0'就是 ASCII 码为 0 的字符,对应的字符是(Null),表示"字符串结束符",是字符串结束的标志。由于在数组的末尾存储了空字符,所以字符数组的大小比字符数多一个。

char name[8] = {'C', 'J', 'A', 'V', 'A', 'P','Y', '\0'};

也可以直接使用字符串初始化:

char name[] = "CJAVAPY";

需要把 null 字符(\0)放在字符串常量的末尾。编译器会在初始化数组时,自动把 \0 放在字符串的末尾。

例如,

#include using namespace std;int main (){  char name[8] = {'C', 'J', 'A', 'V', 'A', 'P','Y', '\0'};  //char name[] = "CJAVAPY";  cout << "www.wonhero.com is : " << name << endl;  return 0;}

2、字符串的函数

strcpy(s1, s2):复制字符串 s2 到字符串 s1。

strcat(s1, s2):连接字符串 s2 到字符串 s1 的末尾。

strlen(s1):返回字符串 s1 的长度。

strcmp(s1, s2):如果 s1 和 s2 是相同的,则返回 0;如果 s1 则返回小于 0;如果 s1>s2 则返回大于 0

strchr(s1, ch):返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。

strstr(s1, s2):返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。

例如,

#include using namespace std;#include int main (){   char str1[14] = "wonhero";   char str2[14] = "csharp";   char str3[14];   int  len ;   /* 复制 str1 到 str3 */   strcpy(str3, str1);    cout << "strcpy( str3, str1) :  " << str3 << endl;   /* 连接 str1 和 str2 */   strcat( str1, str2);    cout << "strcat( str1, str2):  " << str1 << endl;   /* 连接后,str1 的总长度 */   len = strlen(str1);   cout << "strlen(str1) :  " << len << endl;   return 0;}

3、String 类字符串

C++ 标准库提供了 string 类类型,支持上述所有的操作,另外还增加了其他更多的功能。string是C++标准库的一个重要的部分,主要用于字符串处理。可以使用输入输出流方式直接进行string操作,也可以通过文件等手段进行string操作。同时,C++的算法库对string类也有着很好的支持,并且string类还和c语言的字符串之间有着良好的接口。

例如,

1)string转换为char*

#include #include #include  using namespace std; int main(){    string strOutput = "Hello World";     cout << "[cout] strOutput is: " << strOutput << endl;     // string 转换为 char*    const char* pszOutput = strOutput.c_str();        printf("[printf] strOutput is: %s\n", pszOutput);     return 0;}

2)string方法示例

#include #include #define HELLOSTR "Hello World"using namespace std; int main(){    string strOutput = "Hello World";     int nLen = strOutput.length();     cout << "the length of strOutput is: " << nLen << endl;     if (0 == strOutput.compare(HELLOSTR))    {    cout << "strOutput equal with macro HELLOSTR" << endl;    }     return 0;}


harset="UTF-8" id="LA_COLLECT" src="//sdk.51.la/js-sdk-pro.min.js"> cript>LA.init({ id: "Jzndc69N7BtnPgpT", ck: "Jzndc69N7BtnPgpT" })