【C++】string类的使用④(字符串操作String operations )

简介: 这篇博客探讨了C++ STL中`std::string`的几个关键操作,如`c_str()`和`data()`,它们分别返回指向字符串的const char*指针,前者保证以'\0'结尾,后者不保证。`get_allocator()`返回内存分配器,通常不直接使用。`copy()`函数用于将字符串部分复制到字符数组,不添加'\0'。`find()`和`rfind()`用于向前和向后搜索子串或字符。`npos`是string类中的一个常量,表示找不到匹配项时的返回值。博客通过实例展示了这些函数的用法。

前言

本篇博客主要内容:STL库中string的字符串操作(String operations)和常量成员(Member constants)

来到string类的使用第四篇,继续我们的内容,本篇博客将着重介绍如何使用string类提供的接口函数去查找和获取字符串的内容;同时还会讲一个定义在string类中的常量成员(npos)
本篇也将是string类使用的收尾篇。

🔥字符串操作(String operations)

在这里插入图片描述

这些接口函数提供的是一些查找和获取string串内容的功能。

==c_str==

在这里插入图片描述
const char* c_str() const;
返回一个指向字符串数组(以'\0'结尾)的指针,代表当前string串的内容

同时返回指针指向的字符串中的内容也是不可修改的

使用案例:

// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
   
   
    std::string str("hello world!");

    char* cstr = new char[str.length() + 1];
    strcpy(cstr, str.c_str());

    printf("%s\n", str.c_str());
    printf("%s\n", cstr);
    return 0;
}

在这里插入图片描述

简单来说c_str就是获取一个字符串指针,指向的就是string对量串中的内容。

==data==

在这里插入图片描述
const char* data() const;
返回一个指向数组的指针。(该数组与string串构成字符相同,不保证字符串数组以'\0'结尾。c_str能保证

使用案例:

// string::data
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
   
   
    int length;

    std::string str = "Test string";
    const char* cstr = "Test string";

    if (str.length() == strlen(cstr))
    {
   
   
        cout << "str and cstr have the same length.\n";

        if (memcmp(cstr, str.data(), str.length()) == 0)
            cout << "str and cstr have the same content.\n";
    }
    return 0;
}

在这里插入图片描述

==get_allocator==

在这里插入图片描述
allocator_type get_allocator() const;
此函数接口返回一个引用到该字符对象的内存分配器(alloctor)的副本。这个分配器用于管理std::string内部数据的内存分配和释放
通常,你不需要使用此函数,编译器能帮你很好的管理好STL库中内存的分配与释放,除非你需要进行一些高级的,与内存管理相关的操作。

实际中并不常用,故不做过多讲解。

==copy==

在这里插入图片描述
size_t copy (char* s, size_t len, size_t pos = 0) const;
将一个string串从pos位置开始跨越len个长度的子串内容拷贝到s指向的数组中(子串len的长度包括pos位置的字符)

返回值:从string串中拷贝到s中字符的个数,这个数字可以等于lenlength()-pos(如果string对象串的长度小于pos+len)。

注:这个接口函数不会在拷贝完的字符串结尾自动加'\0'

使用案例:

// string::copy
#include <iostream>
#include <string>
using namespace std;
int main()
{
   
   
    char buffer[20];
    string str("Test string...");
    size_t length = str.copy(buffer, 6, 5);
    buffer[length] = '\0';
    cout << "buffer contains: " << buffer << '\n';
    return 0;
}

在这里插入图片描述

==find==

在这里插入图片描述

提供了在string串中按顺序查找某字符和某子串的功能。

(1) string
size_t find (const string& str, size_t pos = 0) const;
从pos位置开始查找string串中是否包含str串。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos(可以看作是一个很大的值,可以提前看下文末的常量成员内容)。
(2) c-string
size_t find (const char* s, size_t pos = 0) const;
从pos位置开始查找string串中是否包含字符串s。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos。
(3) buffer
size_t find (const char* s, size_t pos, size_t n) const;
从pos位置开始查找string串中是否包含字符串s的前n个字符组成的子串。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos。
(4) character
size_t find (char c, size_t pos = 0) const;
从pos位置开始查找string串中是否包字符c。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos。

使用案例:

// string::find
#include <iostream>       // std::cout
#include <string>         // std::string
using namespace std;
int main()
{
   
   
    string str("There are two needles in this haystack with needles.");
    string str2("needle");

    // different member versions of find in the same order as above:
    size_t found = str.find(str2);
    if (found != string::npos)
        cout << "first 'needle' found at: " << found << '\n';

    found = str.find("needles are small", found + 1, 6);
    if (found != string::npos)
        cout << "second 'needle' found at: " << found << '\n';

    found = str.find("haystack");
    if (found != string::npos)
        cout << "'haystack' also found at: " << found << '\n';

    found = str.find('.');
    if (found != string::npos)
        cout << "Period found at: " << found << '\n';

    // let's replace the first needle:
    str.replace(str.find(str2), str2.length(), "preposition");
    cout << str << '\n';

    return 0;
}

在这里插入图片描述

==rfind==

在这里插入图片描述

这个函数就是从后往前找的find,功能我就不多做赘述了。

(1) string
size_t rfind (const string& str, size_t pos = npos) const;
(2) c-string
size_t rfind (const char* s, size_t pos = npos) const;
(3) buffer
size_t rfind (const char* s, size_t pos, size_t n) const;
(4) character
size_t rfind (char c, size_t pos = npos) const;

注:当pos被确定时,rfind会忽略任何在pos之后的字符。

使用案例:

// string::rfind
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main()
{
   
   
    string str("The sixth sick sheik's sixth sheep's sick.");
    string key("sixth");

    size_t found = str.rfind(key);
    if (found != string::npos)
        str.replace(found, key.length(), "seventh");

    cout << str << '\n';

    return 0;
}

在这里插入图片描述

相关文章
|
8月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
456 100
|
8月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
611 99
|
8月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
8月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
9月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
430 92
|
10月前
|
C语言 C++
【实战指南】 C/C++ 枚举转字符串实现
本文介绍了在C/C++中实现枚举转字符串的实用技巧,通过宏定义与统一管理枚举名,提升代码调试效率并减少维护错误。
559 93
|
7月前
|
编解码 Java 开发者
Java String类的关键方法总结
以上总结了Java `String` 类最常见和重要功能性方法。每种操作都对应着日常编程任务,并且理解每种操作如何影响及处理 `Strings` 对于任何使用 Java 的开发者来说都至关重要。
431 5
|
10月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
479 14