字符串
●【1】字符数组
在 C++ 中,字符数组是一种特殊的数组类型,用于存储一串字符。字符数组在程序中广泛应用,例如存储字符串、输入输出字符串、处理字符串等,需要头文件#include <cstring>
。
定义一个字符数组的基本语法如下:
char str[] = "hello world"; // 可以指定长度也可以不指定长度
在上述示例中,定义了一个名为 str
的字符数组,用于存储字符串 "hello world"。由于字符数组的长度是不确定的,因此可以省略数组长度。
可以使用下标运算符 []
访问字符数组中的元素。例如:
char ch = str[0]; // 将字符数组的第一个字符赋值给变量 ch
字符串输入输出
在 C++ 中,可以使用输入输出流对象 cin
和 cout
进行字符串的输入输出。
使用 cin
进行字符串的输入时,可以使用 getline()
函数,该函数会读取一行字符串(包括空格),并将其存储到字符数组中。例如:
char str[100]; cout << "请输入一个字符串:" << endl; cin.getline(str, 100); cout << "输入的字符串为:" << str << endl;
在上述示例中,使用 cin.getline()
函数读取一行字符串,并将其存储到名为 str
的字符数组中。然后使用 cout
输出该字符数组中的内容。
使用 cout
进行字符串的输出时,可以直接输出字符数组的名称,该操作会将整个字符数组中的内容输出到屏幕上。例如:
char str[] = "hello world"; cout << str << endl;
字符数组处理函数
-
strlen()
函数:返回字符数组中的字符串长度(不包括空字符\0
)。#include <iostream> #include <cstring> using namespace std; int main(){ char str[] = "hello world"; int len = strlen(str); cout << "字符串长度为:" << len << endl; return 0; }
在上述示例中,使用
strlen()
函数获取字符串 "hello world" 的长度,并将其赋值给变量len
,然后输出字符串长度。 -
strcpy()
函数:将一个字符数组中的字符串复制到另一个字符数组中。#include <iostream> #include <cstring> using namespace std; int main(){ char str1[] = "hello world"; char str2[20]; strcpy(str2, str1); cout << "复制后的字符串为:" << str2 << endl; return 0; }
在上述示例中,使用
strcpy()
函数将字符数组str1
中的字符串复制到字符数组str2
中,并输出复制后的字符串。 -
strcat()
函数:将一个字符数组中的字符串连接到另一个字符数组中。#include <iostream> #include <cstring> using namespace std; int main(){ char str1[20] = "hello "; char str2[] = "world"; strcat(str1, str2); cout << "连接后的字符串为:" << str1 << endl;