- robin 的博客
第二章程序设计基础知识 第5节 字符数组与字符串
- @ 2025-6-24 21:35:04
第二章 程序设计基础知识
第5节 字符数组与字符串
字符串实际上是用null字符即'\0'终止的一维字符数组。内容固定的字符串叫字符串常量,它用双引号括起来,而字符常量用单引号括起来。即使一个字符的字符串也不是字符类型,因为字符串末尾有'\0'作为结束符。
C++提供了两种类型的字符串表示形式:
- C语言风格的字符串,在头文件cstring中;
- C++引入的string类,在头文件string中。
一、C风格字符串
- 字符数组
#include<cstdio>
using namespace std;
int main() {
char str[] = "I love china";
printf("%s\n", str);
return 0;
}
- 字符指针
#include<cstdio>
using namespace std;
int main() {
char *str = "I love china";
printf("%s\n", str);
return 0;
}
二、C++引入的string类
C++标准库提供了string类类型,支持上述所有C风格字符串操作。
#include<iostream>
#include<string>
using namespace std;
int main() {
string s1 = "Hello";
string s2 = "world";
string s3;
int len;
s3 = s1; // 赋值s1到s3
cout << "s3:" << s3 << endl;
s3 = s1 + s2; // 连接s1和s2
cout << "s1 + s2:" << s3 << endl;
len = s3.size(); // 连接后s3的总长度
cout << "s3.size():" << len << endl;
return 0;
}
三、字符数组和字符串相关函数总结
-
字符数组相关函数总结

-
字符串(stl容器)相关函数总结
