C++ string and string_view(这篇教你怎么用)

C++ string and string_view

string(不可变字符串)

string 变量定义

char text[] = "dada";
std::string str1;	      // 声明变量,默认为空字符串 ""
str1 = text;			  // str1 = "dada"
std::string str2{
    
    "ddd"}; // str2 = "ddd"
std::string str3 = str2; // 用 str2 初始化 str1

string 输入输出

std::string str1;
// 输入空格后面的字符串无法输出,因为 cin 遇到空格后就默认输入结束
std::cin>>str1;
std::cout<<str1;
// 采用下面这种形式则可以输入并显示空格
std::getline(std::cin, str2);
std::cout<<str2;

string 求长度

std::string str {
    
    "djaljl"};
auto len = str.length();	// len = 6

string c++ 转化为 c 风格字符串

std::string str1 {
    
    "fdafaga"};
auto str2 {
    
     str1 };
auto str3 = str2.c_str();

string 访问单个字符

std::string str {
    
    "ffgz"};
for(int i = 0; i < str.length(); ++i){
    
    	// for 赋值
	str[i] = 't';
	}
for(const auto& c : str){
    
    
	std::cout << c << ' ';  // foreach 输出

string 字符串拼接

std::string str1 = "ddd";
std::string str2 = "aaa";
auto str3 = str1 + str2;	// 两字符串拼接
str3 += 'd';				// 拼接单个字符
char d = 'n';
str3 += d; 					// str3 = "dddaaadn"

string 插入

std::string str = "aeiou";
str.insert(3, "dd");		// 在下标为 3 的位置插入 "dd", str = "aeiddou"

string 删除

std::string str{
    
    "aeiougg"};
str.erase(2, 3);	// 删除下标为 2 开始后的三个字符, str = "aegg" 
                   	// 不指明长度则将下标位置后的字符全部删除, 如果长度越界也是删除后面的全部字符

string 提取子字符串

std::string str1 {
    
    "aeiouabcdef"};
auto str2 = str1.substr(3,5);	// 提取下标为 3 开始, 长度为 5 的子串 str2 = "ouabc"

string 查找子串

std::string str {
    
    "aeiouabcdd"};
// find()
int index = str.find("abc"); 	// 返回的子字符串第一次出现在字符串中的起始下标 index = 5
								// 默认从第一的字符(下标为 0 的位置)开始查找
								// 没有找到返回一个无穷大值 4294967295
index = str.find("bcd", 4);		// index = 6, 第二个参数表示从下标为 4 的地方开始查找 

// rfind()
int rindex = str.rfind("abc", 6); // rindex = 5, 从下标 0 开始查找到下标 6
								  // 若做找到则返回, 未找到则返回无穷大值 4294967295

// find_first_of()
auto s {
    
    "string"};
int findex = str.find_first_of(s);	// 返回 str 和 s 字符串共有的字符(i)在 str 中第一次出现的下标 findex = 2

string → string_view(可变字符串)

string_view 声明及定义

char text[] = "text";
std::string_view str{
    
     text };
std::string_view more{
    
     str };	// more = "text"

string_view 长度

std::string_view str_view {
    
    "ddddd"};
auto len = str_view.length();	// len = 5

string_view 修改字符串

std::string_view str1 {
    
    "abc"};
auto str2 {
    
    str1};
str2[1] = 's'; 	// str1 = str2 = "asc"

string_view 的其他行为

自主学习

猜你喜欢

转载自blog.csdn.net/weixin_48033173/article/details/112269768