【C++】字符串学习 知识点+代码记录

发布于:2024-07-19 ⋅ 阅读:(166) ⋅ 点赞:(0)

一.知识点总结

1. C风格字符串(字符数组)

  • 字符数组存储字符串:C风格的字符串实际上是字符数组,以空字符'\0'作为结尾标志。
  • 字符串字面量与字符数组:字符串字面量如"Hello"被编译器视为const char*类型,可以直接赋值给指向char的指针或字符数组。
  • 初始化字符数组:可以通过初始化列表或字符串字面量初始化字符数组,后者会在数组末尾自动添加'\0'

2. C++标准库std::string

  • 字符串对象声明std::string类提供了一种更安全、更灵活的方式来处理字符串。
  • 字符串操作std::string类提供了丰富的成员函数来操作字符串,如appendassigncompareinsertsubstrfindlength, 和 swap
    • append:在字符串末尾添加另一个字符串或字符序列。
    • assign:将字符串的内容替换为一个新的字符串或字符序列。
    • compare:比较两个字符串,返回值指示了字符串的字典序关系。
    • insert:在指定位置插入新的字符串或字符序列。
    • substr:提取字符串的一部分,返回子字符串。
    • find:搜索字符串中首次出现的字符或子字符串的位置。
    • length:返回字符串的长度(不包括结尾的'\0')。
    • swap:交换两个std::string对象的内容。

3. 字符串的输出与访问

  • 输出字符串:无论是C风格字符串还是std::string对象,都可以直接使用cout进行输出。
  • 访问字符串元素std::string对象支持通过索引访问单个字符,如str[i]

4. 注意事项

  • 字符串字面量和数组初始化:在C++中,不能使用初始化列表int* INT = {1,2,3};来初始化指针,因为这违反了C++的规则,不同于字符数组的初始化。
  • 字符串常量与指针:字符串字面量被编译器视为const char*,这意味着你不能修改字符串字面量中的字符。

二.详细注释代码

//与C语言一样,C++的基本数据类型变量中没有字符串变量
#include<iostream>
#include<string>
using namespace std;

int main() {
	//字符数组储存(较繁琐)
	//字符串常量赋给字符串指针
	//一个字符串常量表示一个字符数组的首地址
	const char* STRING1 = "HEllo WOrld";
	//直接输出
	cout << STRING1 << endl;
	//错误int* INT = {1,2,3};
	//三种等价初始化格式
	char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
	char str2[6] = "Hello";//末尾隐含有'\0'
	char str3[] = "World";

	//string类
	//常用成员函数
	const char* s = "EXO";
	string a = "Hello";
	string b = "World~";
	cout << "a : " << a << "  b : " << b << " s : " << s << endl;
	//添加在串尾
	a.append(s);
	cout << "a.append(s) : " << a << endl;
	//赋值
	a.assign(s);
	cout << "a.assign(s) : " << a << endl;
	//比较大小,本串 较小返回负数,较大返回正数,否则返回0
	cout << "a.compare(s) : " << a.compare(s) << endl;
	cout << "a.compare(b) : " << a.compare(b) << endl;
	//s串插在整数对应下标之前
	a.insert(2, s);
	cout << "a.insert(2, s) : " << a << endl;
	a.insert(4, s);
	cout << "a.insert(4, s) : " << a << endl;
	//从第一个位置取第二个位置的个数返回新串(取子串)
	string c = a.substr(2, 3);
	cout << "c = a.substr(2, 3) : " << c << endl;
	//查找第一次出现的位置
	cout << "a.find('O') : " << a.find('O') << endl;
	cout << "a.find(c) : " << a.find(c) << endl;
	//返回串长度
	cout << "a.length() : " << a.length() << endl;
	//将本串与其进行交换
	cout << "a: " << a << " b: " << b << endl;
	cout << "a.swap(b) : " << endl;
	a.swap(b);
	cout << "a: " << a << " b: " << b << endl;

}

三.输出

HEllo WOrld
a : Hello  b : World~ s : EXO
a.append(s) : HelloEXO
a.assign(s) : EXO
a.compare(s) : 0
a.compare(b) : -1
a.insert(2, s) : EXEXOO
a.insert(4, s) : EXEXEXOOO
c = a.substr(2, 3) : EXE
a.find('O') : 6
a.find(c) : 0
a.length() : 9
a: EXEXEXOOO b: World~
a.swap(b) :
a: World~ b: EXEXEXOOO


网站公告

今日签到

点亮在社区的每一天
去签到