存储字符的序列 | c++字符串
2025-09-20 13:37:38
发布于:江西
字符串是存储字符的序列,在c++中,有两种字符串类型:C风格字符串char和string。
1.C风格字符串
1.1.头文件
C风格字符串使用时需包含头文件<cstring>:
#include <cstring>
1.2.赋值
C风格字符串赋值与数组相似:
char ch[5] = "char"; :定义一个长度为5的字符数组。
注意 :C风格字符串以\0(空字符)结尾,即使你不加上它,编译器在编译时也会自己加上的,因此,声明字符数组时设置的长度应比字符数要多。
1.3.长度
strlen(ch):返回字符数组ch的长度(字符数,不含末尾\0)
1.4.复制
strcpy(dest, ch):将dest赋值为ch的值。
1.5.拼接
strcat(dest, ch):将ch的内容拼接在dest的后面。
1.6.判等
strcmp(ch1, ch2):当两个字符数组相同时返回0,不相同返回1。
1.7.示例代码:
#include <cstring> // C风格字符串头文件
#include <iostream> // IO流头文件
using namespace std;
int main() {
char s1[20] = "hello";
char s2[20] = "world";
// 拼接
strcat(s1, " ");
strcat(s1, s2);
cout << s1 << endl; // 输出"hello world"
// 判等
if (!strcmp(s1, "hello world")) {
cout << "s1 == hello world" << endl;
}
return 0;
}
2.string类
2.1.头文件
需导入string类:
#include <string>
2.2.赋值
string s1 = "hello"; // 将s1赋值为“hello”
string s2 = s1; // 将s2赋值为s1的值
注意 :string和C风格不同,string的末尾没有\0!
2.3.拼接
s1 += " world"; // "hello world"
s1 = s1 + " world"; // "hello world world"
s1.append('.'); // "hello world world."
2.4.长度
s1.length() 或 s1.size():返回size_t类型。
2.5.下标
s1[0](下标从0开始,越界行为未定义):返回s1的第一个字符(下标0)。
2.6.查找子串
s1.find("world")(从左开始,返回子串第一次出现的起始下标,未找到返回string::npos)。
s1.rfind("world")(从右开始,返回子串第一次出现的起始下标,未找到返回string::npos)。
2.7.截取字串
s1.substr(2, 5):从下标2开始,截取5个字符并返回,如果第2个参数越界则截取剩余所有字符。
2.8.示例代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
// 长度
cout << "长度:" << s.size() << endl; // 输出11
// 下标
cout << "第6个字符:" << s[5] << endl; // 输出' '(空格)
// 查找子串
size_t pos = s.find("world");
if (pos != string::npos) {
cout << "找到子串,起始位置:" << pos << endl; // 输出6
}
return 0;
}
创作不易,支持一下吧!!!
全部评论 2
cstring在C++中是char数组的操作方式
2025-10-01 来自 福建
0没写错啊
2025-10-02 来自 江西
0一个是cstring,一个是string
2025-10-02 来自 江西
0
那啥有点浅
2025-10-01 来自 浙江
0额
2025-10-01 来自 江西
0














有帮助,赞一个