【C++】string类的使用③(非成员函数重载Non-member function overloads)

简介: 这篇文章探讨了C++中`std::string`的`replace`和`swap`函数以及非成员函数重载。`replace`提供了多种方式替换字符串中的部分内容,包括使用字符串、子串、字符、字符数组和填充字符。`swap`函数用于交换两个`string`对象的内容,成员函数版本效率更高。非成员函数重载包括`operator+`实现字符串连接,关系运算符(如`==`, `<`等)用于比较字符串,以及`swap`非成员函数。此外,还介绍了`getline`函数,用于按指定分隔符从输入流中读取字符串。文章强调了非成员函数在特定情况下的作用,并给出了多个示例代码。

==replace==

在这里插入图片描述

函数大体功能是将当前对象串中的一段字符串或字符用另一段字符串或字符替换。

(1) string
string& replace (size_t pos, size_t len, const string& str);
string& replace (iterator i1, iterator i2, const string& str);
将当前对象相应位置替换为str
(2) substring
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
将当前对象相应位置替换为str对象由subpos位置开始,跨越sublen的子串(如果len过大超出串的范围,则取到str的末尾)
(3) c-string
string& replace (size_t pos, size_t len, const char* s);
string& replace (iterator i1, iterator i2, const char* s);
将当前对象相应位置替换为s指向(由'\0'字符结尾)的字符串
(4) buffer
string& replace (size_t pos, size_t len, const char* s, size_t n);
string& replace (iterator i1, iterator i2, const char* s, size_t n);
将当前对象相应位置替换为s指向的前n个字符组成字符串
(5) fill
string& replace (size_t pos, size_t len, size_t n, char c);
string& replace (iterator i1, iterator i2, size_t n, char c);
将当前对象相应位置替换为n个char类型的c字符
(6) range
template <class InputIterator>
string& replace (iterator i1, iterator i2, InputIterator first, InputIterator last);
将当前对象相应位置替换为迭代器区间[first,last)内的字符序列*

使用案例:

// replacing in a string
#include <iostream>
#include <string>
using namespace std;
int main()
{
   
   
    string base = "this is a test string.";
    string str2 = "n example";
    string str3 = "sample phrase";
    string str4 = "useful.";

    // replace signatures used in the same order as described above:

    // Using positions:                 0123456789*123456789*12345
    string str = base;           // "this is a test string."
    str.replace(9, 5, str2);          // "this is an example string." (1)
    str.replace(19, 6, str3, 7, 6);     // "this is an example phrase." (2)
    str.replace(8, 10, "just a");     // "this is just a phrase."     (3)
    str.replace(8, 6, "a shorty", 7);  // "this is a short phrase."    (4)
    str.replace(22, 1, 3, '!');        // "this is a short phrase!!!"  (5)

    // Using iterators:                                               0123456789*123456789*
    str.replace(str.begin(), str.end() - 3, str3);                    // "sample phrase!!!"      (1)
    str.replace(str.begin(), str.begin() + 6, "replace");             // "replace phrase!!!"     (3)
    str.replace(str.begin() + 8, str.begin() + 14, "is coolness", 7);    // "replace is cool!!!"    (4)
    str.replace(str.begin() + 12, str.end() - 4, 4, 'o');                // "replace is cooool!!!"  (5)
    str.replace(str.begin() + 11, str.end(), str4.begin(), str4.end());// "replace is useful."    (6)
    cout << str << '\n';
    return 0;
}

在这里插入图片描述

==swap==

在这里插入图片描述
void swap (string& str);
交换两个string对象的内容

使用案例:

#include<iostream>
#include<string>
using namespace std;
int main()
{
   
   
    string str1("hello");
    string str2("world");
    cout << str1 << endl;
    cout << str2 << endl;

    str1.swap(str2);

    cout << endl;
    cout << str1 << endl;
    cout << str2 << endl;
    return 0;
}

在这里插入图片描述

注:此函数比algorithm提供的swap交换更优,是string交换的最优方式。故交换string对象时尽量使用此方法。

🔥非成员函数重载(Non-member function overloads)

在这里插入图片描述

非成员函数重载,是作为string类的友元函数,在类的外面定义和实现,通过类型来匹配非成员函数。

==operator+==

在这里插入图片描述
这里其实不用过多赘述,六个重载实现了string对象相加的功能(string对象+字符串,string对象+字符,字符串+string对象,字符+string对象,string对象+string对象)。

注:没有 -> 字符串+字符串

代码案例:

// concatenating strings
#include <iostream>
#include <string>
using namespace std;
int main()
{
   
   
    string firstlevel("com");
    string secondlevel("cplusplus");
    string scheme("http://");
    string hostname;
    string url;

    hostname = "www." + secondlevel + '.' + firstlevel;
    url = scheme + hostname;

    cout << url << '\n';
    return 0;
}

在这里插入图片描述

==relation operators(string)==

在这里插入图片描述

重载了string对象之间进行比较大小的功能,比较规则就是字典序。

代码案例:

// string comparisons
#include <iostream>
#include <vector>
using namespace std;
int main()
{
   
   
    string foo = "alpha";
    string bar = "beta";

    if (foo == bar) cout << "foo and bar are equal\n";
    if (foo != bar) cout << "foo and bar are not equal\n";
    if (foo < bar) cout << "foo is less than bar\n";
    if (foo > bar) cout << "foo is greater than bar\n";
    if (foo <= bar) cout << "foo is less than or equal to bar\n";
    if (foo >= bar) cout << "foo is greater than or equal to bar\n";

    return 0;
}

在这里插入图片描述

==swap(string)==

在这里插入图片描述
交换strirng对象

代码案例:

#include<iostream>
#include<string>
using namespace std;
int main()
{
   
   
    string str1("hello");
    string str2("world");
    cout << str1 << endl;
    cout << str2 << endl;

    swap(str1, str2);

    cout << endl;
    cout << str1 << endl;
    cout << str2 << endl;
    return 0;
}

在这里插入图片描述

此非成员函数也可以实现string对象的交换,但是这个实现与重载在string类中的不同,string对象在交换串的时候是改变指针指向交换的。而这里的swap是使用tmp存储临时对象的方式实现交换,增大了内存开销。

==流插入和流提取重载==

在这里插入图片描述
控制台输入将内容读取到string对象中
在这里插入图片描述
将内容输入到控制台

使用案例:

// inserting strings into output streams
#include <iostream>
#include <string>
using namespace std;
int main()
{
   
   
    string str;
    cin >> str;
    cout << str << '\n';
    return 0;
}

在这里插入图片描述

注:cin的读入是按照空格和换行进行分隔的,当你输入hello world时,使用上面的cin只能读取到hello。
如下:
在这里插入图片描述
当面对这种情况时,就需要我们的getline出手了。

==getline==

在这里插入图片描述
功能和cin相同,但可以通过此函数更改字符串读取时的分隔方式。

(1)
istream& getline (istream& is, string& str, char delim);
当你传第三个参数时,调用此函数,会以delim为分隔符进行分隔
(2)
istream& getline (istream& is, string& str);
当不传第三个参数,会默认以'\n'为分隔符

使用案例:

// extract to string
#include <iostream>
#include <string>
using namespace std;
int main()
{
   
   
    string name;

    cout << "Please, enter your full name: ";
    getline(cin, name);
    cout << "Hello, " << name << "!\n";

    return 0;
}

在这里插入图片描述

结语

本篇博客,介绍了关于string的修改器,能修改string串中的内容;以及非成员函数的重载,实现了一些成员函数无法完成的功能和任务
博主会继续分享关于string类的使用以及STL更多的内容,感谢大家的支持。♥

相关文章
|
存储 安全 C语言
C++ String揭秘:写高效代码的关键
在C++编程中,字符串操作是不可避免的一部分。从简单的字符串拼接到复杂的文本处理,C++的string类为开发者提供了一种更高效、灵活且安全的方式来管理和操作字符串。本文将从基础操作入手,逐步揭开C++ string类的奥秘,帮助你深入理解其内部机制,并学会如何在实际开发中充分发挥其性能和优势。
|
对象存储 C++ 容器
c++的string一键介绍
这篇文章旨在帮助读者回忆如何使用string,并提醒注意事项。它不是一篇详细的功能介绍,而是一篇润色文章。先展示重载函数,如果该函数一笔不可带过,就先展示英文原档(附带翻译),最后展示代码实现与举例可以直接去看英文文档,也可以看本篇文章,但是更建议去看英文原档。那么废话少说直接开始进行挨个介绍。
224 3
|
人工智能 Python
083_类_对象_成员方法_method_函数_function_isinstance
本内容主要讲解Python中的数据类型与面向对象基础。回顾了变量类型(如字符串`str`和整型`int`)及其相互转换,探讨了加法在不同类型中的表现。通过超市商品分类比喻,引出“类型”概念,并深入解析类(class)与对象(object)的关系,例如具体橘子是橘子类的实例。还介绍了`isinstance`函数判断类型、`type`与`help`探索类型属性,以及`str`和`int`的不同方法。最终总结类是抽象类型,对象是其实例,不同类型的对象有独特运算和方法,为后续学习埋下伏笔。
305 7
083_类_对象_成员方法_method_函数_function_isinstance
|
Python
[oeasy]python086方法_method_函数_function_区别
本文详细解析了Python中方法(method)与函数(function)的区别。通过回顾列表操作如`append`,以及随机模块的使用,介绍了方法作为类的成员需要通过实例调用的特点。对比内建函数如`print`和`input`,它们无需对象即可直接调用。总结指出方法需基于对象调用且包含`self`参数,而函数独立存在无需`self`。最后提供了学习资源链接,方便进一步探索。
345 17
|
人工智能 Python
[oeasy]python083_类_对象_成员方法_method_函数_function_isinstance
本文介绍了Python中类、对象、成员方法及函数的概念。通过超市商品分类的例子,形象地解释了“类型”的概念,如整型(int)和字符串(str)是两种不同的数据类型。整型对象支持数字求和,字符串对象支持拼接。使用`isinstance`函数可以判断对象是否属于特定类型,例如判断变量是否为整型。此外,还探讨了面向对象编程(OOP)与面向过程编程的区别,并简要介绍了`type`和`help`函数的用法。最后总结指出,不同类型的对象有不同的运算和方法,如字符串有`find`和`index`方法,而整型没有。更多内容可参考文末提供的蓝桥、GitHub和Gitee链接。
364 11
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
553 12
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
289 0