C++奇迹之旅:string类对象的修改操作

发布于:2024-05-08 ⋅ 阅读:(29) ⋅ 点赞:(0)

请添加图片描述


📝string类的常用接口

string网址查询:https://legacy.cplusplus.com/reference/string/string/

🌠 string类对象的修改操作

函数名称 功能说明
push_back 在字符串后尾插字符c
append 在字符串后追加一个字符串
operator+= (重点) 在字符串后追加字符串str
c_str(重点) 返回C格式字符串
find + npos(重点) 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr 在str中从pos位置开始,截取n个字符,然后将其返回

🌉push_back

在这里插入图片描述
将字符 c 追加到字符串的末尾,将其长度增加 1

string s1("hello world");
cout << s1 << endl;
cout << s1.size() << endl;

s1.push_back('x');
cout << s1 << endl;
cout << s1.size() << endl;

在这里插入图片描述

🌉append

在这里插入图片描述

  1. 在字符串后追加字符串
string s2("hello world");
s2.append(" yyyyyy");
cout << s2 << endl;
cout << s2.size() << endl;
cout << endl;

在这里插入图片描述

string s1("hello String");
s1.push_back('!');
cout << s1 << endl;

string s2("hello world");
s2.append(" yyyyyy");
cout << s2 << endl;
cout << s2.size() << endl;
cout << endl;

s1.append(s2);
cout << s2 << endl;

在这里插入图片描述

  1. 可以使用迭代器取某一部分字符串
string s1("hello String");
string s2("hello world");
s1.append(s2.begin() + 6, s2.end());
cout << s1 << endl;

在这里插入图片描述
综合其用法:

string str;
string str2 = "Writing ";
string str3 = "print 10 and then 5 more";

// used in the same order as described above:
str.append(str2);                       // "Writing "
str.append(str3, 6, 3);                   // "10 "
str.append("dots are cool", 5);          // "dots "
str.append("here: ");                   // "here: "
str.append(10u, '.');                    // ".........."
str.append(str3.begin() + 8, str3.end());  // " and then 5 more"

std::cout << str << '\n';
return 0;

在这里插入图片描述

🌉operator+=

在这里插入图片描述
用法:通过在当前值的末尾附加其他字符来扩展字符串:可以追加这string对象,字符串,字符
例子:

string name("John");
string family("Smith");
name += "K ";
name += family;
name += '\n';

cout << name << endl;

在这里插入图片描述

🌉insert

在这里插入图片描述
例如:在字符串中指定位置插入其他字符

string s1("to be question");
string s2("the ");
string s3("or not to be");

s1.insert(6, s2);
cout << s1 << endl;

s1.insert(6, s3, 3, 4);
cout << s1 << endl;

s1.insert(10, "that is cool", 8);
cout << s1 << endl;

在这里插入图片描述

🌉erase

在这里插入图片描述
功能:擦除部分字符串,减少其长度:
三种擦除:顺序擦除,指定擦除,范围擦除

string s1("This is an example sentence.");
cout << s1 << endl;

//顺序擦除
s1.erase(10, 8);
cout << s1 << endl;

//指定擦除
s1.erase(s1.begin() + 9);
cout << s1 << endl;

//范围擦除:擦除 [first,last] 范围内的字符序列。
s1.erase(s1.begin() + 5, s1.end() - 9);
cout << s1 << endl;

在这里插入图片描述

🌉replace

在这里插入图片描述
功能:用新内容替换字符串中从字符 pos 开始并跨越 len 字符的部分(或字符串在 [i1,i2) 之间的部分):

string base("this is a test string.");
string s2("n example");
string s3("sample phrase");

string s1 = base;
s1.replace(9, 5, s2);
cout << s1 << endl;

s1.replace(19, 6, s3, 7, 6);
cout << s1 << endl;

在这里插入图片描述

详细可查看:https://legacy.cplusplus.com/reference/string/string/replace/

🌉 find

在这里插入图片描述

作用:用于在字符串中搜索指定子字符串或字符的第一次出现。
std::string::nposstd::string类的一个静态成员常量,表示当搜索的子字符串或字符未找到时,npos为无效值。

  1. 在字符串中搜索子字符串的位置:
#include <iostream>
#include <string>

int main() 
{
    std::string str = "The quick brown fox jumps over the lazy dog.";
    std::string substr = "brown";

    size_t pos = str.find(substr);
    if (pos != std::string::npos) 
    {
        std::cout << "Found '" << substr << "' at position: " << pos << std::endl;
    } else 
    {
        std::cout << "'" << substr << "' not found in the string." << std::endl;
    }

    return 0;
}

输出:

Found 'brown' at position: 10
  1. 从指定位置开始搜索子字符串:
#include <iostream>
#include <string>

int main() 
{
    std::string str = "The quick brown fox jumps over the lazy dog.";
    std::string substr = "the";

    size_t pos = str.find(substr, 15);
    if (pos != std::string::npos) 
    {
        std::cout << "Found '" << substr << "' at position: " << pos << std::endl;
    } else 
    {
        std::cout << "'" << substr << "' not found in the string." << std::endl;
    }

    return 0;
}

输出:

Found 'the' at position: 36
  1. 搜索字符:
#include <iostream>
#include <string>

int main() 
{
    std::string str = "Hello, World!";
    char c = 'o';

    size_t pos = str.find(c);
    if (pos != std::string::npos) 
    {
        std::cout << "Found '" << c << "' at position: " << pos << std::endl;
    } else {
        std::cout << "'" << c << "' not found in the string." << std::endl;
    }

    return 0;
}

输出:

Found 'o' at position: 4

🌉 c_str

在这里插入图片描述
它返回一个指向字符串内容的 C 风格字符串指针(以 null 字符结尾)。这个函数非常有用,因为它允许你将 std::string 对象传递给需要 C 风格字符串的函数

string str = "Hello,World!";

//使用 c_str() 获取 C 风格字符串
const char* cstr = str.c_str();
cout << cstr << endl;

在这里插入图片描述

🌠测试string


// 测试string:
// 1. 插入(拼接)方式:push_back  append  operator+= 
// 2. 正向和反向查找:find() + rfind()
// 3. 截取子串:substr()
// 4. 删除:erase
void Teststring()
{
	string str;
	str.push_back(' '); // 在str后插入空格
	str.append("Hello");// 在str后追加一个字符"hello"
	str += 'S'; // 在str后追加一个字符'S' 
	str += "tring"; //在str后追加一个字符串"tring"
	cout << str << endl;
	cout << str.c_str() << endl;

	//获取file的后缀
	string file("string.cpp");
	size_t pos = file.rfind('.');
	string suffix(file.substr(pos, file.size() - pos));
	cout << suffix << endl;

	//npos是string里面的一个静态变量
	//static const size_t npos = -1;

	//取出url中的域名
	string url("https://legacy.cplusplus.com/reference/string/string/find/");
	cout << url << endl;
	size_t start = url.find("://");
	if (start == string::npos)
	{
		cout << "invalid url" << endl;
		return;
	}
	start += 3;
	size_t finsh = url.find('/', start);
	string address = url.substr(start, finsh - start);
	cout << address << endl;

	//删除url的协议前缀
	pos = url.find("://");
	url.erase(0, pos + 3);
	cout << url << endl;
}

int main()
{
	Teststring();
	return 0;
}

在这里插入图片描述


🚩总结

注意:

  1. string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般
    情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。
    请添加图片描述