【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更多的内容,感谢大家的支持。♥

相关文章
|
3天前
|
编译器 C++
【C++】string类的使用④(字符串操作String operations )
这篇博客探讨了C++ STL中`std::string`的几个关键操作,如`c_str()`和`data()`,它们分别返回指向字符串的const char*指针,前者保证以&#39;\0&#39;结尾,后者不保证。`get_allocator()`返回内存分配器,通常不直接使用。`copy()`函数用于将字符串部分复制到字符数组,不添加&#39;\0&#39;。`find()`和`rfind()`用于向前和向后搜索子串或字符。`npos`是string类中的一个常量,表示找不到匹配项时的返回值。博客通过实例展示了这些函数的用法。
|
3天前
|
C++
【C++】string类的使用④(常量成员Member constants)
C++ `std::string` 的 `find_first_of`, `find_last_of`, `find_first_not_of`, `find_last_not_of` 函数分别用于从不同方向查找目标字符或子串。它们都返回匹配位置,未找到则返回 `npos`。`substr` 用于提取子字符串,`compare` 则提供更灵活的字符串比较。`npos` 是一个表示最大值的常量,用于标记未找到匹配的情况。示例代码展示了这些函数的实际应用,如替换元音、分割路径、查找非字母字符等。
|
8天前
|
C++
【C++】日期类Date(详解)②
- `-=`通过复用`+=`实现,`Date operator-(int day)`则通过创建副本并调用`-=`。 - 前置`++`和后置`++`同样使用重载,类似地,前置`--`和后置`--`也复用了`+=`和`-=1`。 - 比较运算符重载如`&gt;`, `==`, `&lt;`, `&lt;=`, `!=`,通常只需实现两个,其他可通过复合逻辑得出。 - `Date`减`Date`返回天数,通过迭代较小日期直到与较大日期相等,记录步数和符号。 ``` 这是236个字符的摘要,符合240字符以内的要求,涵盖了日期类中运算符重载的主要实现。
|
3天前
|
C++
C++】string类的使用③(修改器Modifiers)
这篇博客探讨了C++ STL中`string`类的修改器和非成员函数重载。文章介绍了`operator+=`用于在字符串末尾追加内容,并展示了不同重载形式。`append`函数提供了更多追加选项,包括子串、字符数组、单个字符等。`push_back`和`pop_back`分别用于在末尾添加和移除一个字符。`assign`用于替换字符串内容,而`insert`允许在任意位置插入字符串或字符。最后,`erase`函数用于删除字符串中的部分内容。每个函数都配以代码示例和说明。
|
3天前
|
安全 编译器 C++
【C++】string类的使用②(元素获取Element access)
```markdown 探索C++ `string`方法:`clear()`保持容量不变使字符串变空;`empty()`检查长度是否为0;C++11的`shrink_to_fit()`尝试减少容量。`operator[]`和`at()`安全访问元素,越界时`at()`抛异常。`back()`和`front()`分别访问首尾元素。了解这些,轻松操作字符串!💡 ```
|
3天前
|
存储 编译器 Linux
【C++】string类的使用②(容量接口Capacity )
这篇博客探讨了C++ STL中string的容量接口和元素访问方法。`size()`和`length()`函数等价,返回字符串的长度;`capacity()`提供已分配的字节数,可能大于长度;`max_size()`给出理论最大长度;`reserve()`预分配空间,不改变内容;`resize()`改变字符串长度,可指定填充字符。这些接口用于优化内存管理和适应字符串操作需求。
|
3天前
|
C++ 容器
【C++】string类的使用①(迭代器接口begin,end,rbegin和rend)
迭代器接口是获取容器元素指针的成员函数。`begin()`返回首元素的正向迭代器,`end()`返回末元素之后的位置。`rbegin()`和`rend()`提供反向迭代器,分别指向尾元素和首元素之前。C++11增加了const版本以供只读访问。示例代码展示了如何使用这些迭代器遍历字符串。
|
3天前
|
存储 编译器 C语言
【C++】string类的使用①(默认成员函数
本文介绍了C++ STL中的`string`类,它是用于方便地操作和管理字符串的类,替代了C语言中不便的字符数组操作。`string`基于`basic_string`模板,提供类似容器的接口,但针对字符串特性进行了优化。学习资源推荐[cplusplus.com](https://cplusplus.com/)。`string`类提供了多种构造函数,如无参构造、拷贝构造、字符填充构造等,以及析构函数和赋值运算符重载。示例代码展示了不同构造函数和赋值运算符的用法。
|
3天前
|
编译器 C++
【C++】类和对象⑤(static成员 | 友元 | 内部类 | 匿名对象)
📚 C++ 知识点概览:探索类的`static`成员、友元及应用🔍。
|
3天前
|
C++
C++基础知识(四:类的学习)
类指的就是对同一类对象,把所有的属性都封装起来,你也可以把类看成一个高级版的结构体。