C ++字符串

C ++提供以下两种类型的字符串表示 :

  • C风格的字符串.

  • 标准C ++引入的字符串类类型.

C风格字符串

C风格的字符串起源于C语言,并继续在C ++中得到支持.该字符串实际上是一维字符数组,由 null 字符'\0'终止.因此,以null结尾的字符串包含构成字符串后跟 null 的字符.

以下声明和初始化创建一个由单词"Hello"组成的字符串".要将空字符保存在数组的末尾,包含字符串的字符数组的大小比单词"Hello"中的字符数多一个.

 
 char greeting [6] = {'H','e','l','l','o','\ 0'};

如果你遵循数组初始化的规则,那么你可以写下面的语句如下 :

char greeting[] = "Hello";

以下是C/C ++中上面定义的字符串的内存呈现 :

C/C ++中的字符串表示

实际上,不要将空字符放在字符串常量的末尾.初始化数组时,C ++编译器会自动将'\ 0'放在字符串的末尾.让我们尝试打印上面提到的字符串 :

#include <iostream>

using namespace std;

int main () {

   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "Greeting message: ";
   cout << greeting << endl;

   return 0;
}

编译并执行上述代码时,会产生以下结果 :

Greeting message: Hello

C ++支持多种函数来处理以null结尾的字符串 :

Sr.No功能&目的
1

strcpy(s1,s2);

将字符串s2复制到字符串s1中.

2

strcat(s1,s2);

将字符串s2连接到字符串s1的末尾.

3

strlen(s1);

返回字符串的长度s1.

4

strcmp(s1,s2);

如果s1和s2相同,则返回0;如果s1

5

strchr(s1,ch);

返回指向字符串s1中第一个字符ch的指针.

6

strstr(s1,s2);

返回指向字符串s1中第一次出现的字符串s2的指针.

下面的例子使用了上面提到的一些函数 :

#include <iostream>
#include <cstring>

using namespace std;

int main () {

   char str1[10] = "Hello";
   char str2[10] = "World";
   char str3[10];
   int  len ;

   // copy str1 into str3
   strcpy( str3, str1);
   cout << "strcpy( str3, str1) : " << str3 << endl;

   // concatenates str1 and str2
   strcat( str1, str2);
   cout << "strcat( str1, str2): " << str1 << endl;

   // total lenghth of str1 after concatenation
   len = strlen(str1);
   cout << "strlen(str1) : " << len << endl;

   return 0;
}

当编译并执行上述代码时,它产生的结果如下 :

strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

C ++中的String类

标准C ++库提供了一个 string 类类型,它支持上面提到的所有操作,另外更多功能.让我们检查以下示例 :

#include <iostream>
#include <string>

using namespace std;

int main () {

   string str1 = "Hello";
   string str2 = "World";
   string str3;
   int  len ;

   // copy str1 into str3
   str3 = str1;
   cout << "str3 : " << str3 << endl;

   // concatenates str1 and str2
   str3 = str1 + str2;
   cout << "str1 + str2 : " << str3 << endl;

   // total length of str3 after concatenation
   len = str3.size();
   cout << "str3.size() :  " << len << endl;

   return 0;
}

当编译并执行上述代码时,它产生的结果如下 :

str3 : Hello
str1 + str2 : HelloWorld
str3.size() :  10