C++:字符串的基础操作


C++ 字符串

c++提供了两种类型的字符串表示形式:

  • C语言风格字符串
  • C++引入的string类类型

C 风格字符串

C 风格的字符串起源于 C 语言,并在 C++ 中继续得到支持。字符串实际上是使用 null 字符 \0 终止的一维字符数组。因此,一个以 null 结尾的字符串,包含了组成字符串的字符。

下面的声明和初始化创建了一个 BELL 字符串。由于在数组的末尾存储了空字符,所以字符数组的大小比单词 BELL 的字符数多一个。

char site[6] = {'B', 'E', 'L', 'L', '\0'};

依据数组初始化规则,可以把上面的语句写成以下语句:

char site[] = "BELL";

其实,不用把 null 字符放在字符串常量的末尾。C++ 编译器会在初始化数组时,自动把 \0 放在字符串的末尾。

C++风格字符串

C++ 中有大量的函数用来操作以 null 结尾的字符串:

作用 函数 解释
字符串复制 strcpy(str1,str2); 复制字符串 str2 到字符串 str1
字符串连接 strcat(str1,str2); 连接字符串 str2 到字符串 str1 的末尾。连接字符串也可以用 + 号,
例如: string str1 = "bell"; string str2 = "AI"; string str = str1 + str2;
字符串长度 strlen(str1); 返回字符串 str1 的长度。
字符串比较 strcmp(str1,str2); 如果 str1str2 是相同的,则返回 0;如果 str1<str2 则返回值小于 0;如果 str1>str2 则返回值大于 0。
字符查找 strchr(str1, ch); 返回一个指针,指向字符串 str1 中字符 ch 的第一次出现的位置。
字符串查找 strstr(str1,str2); 返回一个指针,指向字符串 str1 中字符串 str2 的第一次出现的位置。

下面的实例使用了上述的一些函数:

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
    char str1[13] = "bell";
    char str2[13] = "AI";
    char str3[13];
    int  len ;
 
    // 复制 str1 到 str3
    strcpy( str3, str1);
    cout << "复制 str1 到 str3 strcpy( str3, str1) : " << str3 << endl;
 	// 字符串比较
	int con1 = strcmp( str1, str2) ;
	int con2 = strcmp( str1, str3) ;
	int con3 = strcmp( str2, str3) ;

	cout << "字符串比较:str1<str2  " << con1 << endl; 
	cout << "字符串比较:str1==str3  " << con2 << endl; 
	cout << "字符串比较:str2>str3  " << con3 << endl; 

    // 连接 str1 和 str2
    strcat( str1, str2);
    cout << "连接 str1 和 str2 strcat( str1, str2): " << str1 << endl;
 
    // 连接后,str1 的总长度
    len = strlen(str1);
    cout << "连接后, str1 的总长度 strlen(str1) : " << len << endl;
	
	// 查找 
    return 0;
}

执行以上代码的结果:

复制 str1 到 str3 strcpy( str3, str1) : bell
字符串比较:str1<str2  1
字符串比较:str1==str3  0
字符串比较:str2>str3  -1
连接 str1 和 str2 strcat( str1, str2): bellAI
连接后, str1 的总长度 strlen(str1) : 6

C++ 中的 String 类

C++ 标准库提供了 **string 类**类型,支持上述所有的操作,另外还增加了其他更多的功能。

示例:

#include <iostream>
#include <string>
using namespace std;
 
int main ()
{
   string str1 = "bell";
   string str2 = "AI";
   string str3;

    cout << "字符串复制前 str3 : " << str3 << endl;
   // 复制 str1 到 str3
   str3 = str1;
   cout << "字符串复制后 str3 : " << str3 << endl;
 
   // 连接 str1 和 str2
   str3 = str1 + str2;
   cout << "字符串连接 str1 + str2 : " << str3 << endl;
 
   // 连接后,str3 的总长度
   cout << "字符串长度 str3.size() :  " << str3.size() << endl;
 
   return 0;
}

运行结果如下:

字符串复制前 str3 :
字符串复制后 str3 : bell
字符串连接 str1 + str2 : bellAI
字符串长度 str3.size() :  6

文章作者: AIL
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 AIL !
评论
  目录