C++ 笔记(22)— STL string 类(字符串赋值、访问、拼接、查找、翻转、大小写转换)

本文详细介绍C++标准模板库(STL)中string类的各种实用操作,包括实例化、赋值、字符访问、拼接、查找、翻转及大小写转换等。通过具体代码示例,读者可以快速掌握如何高效地利用STL string类处理字符串。

1. 实例化和赋值 STL string

#include <string>
#include <iostream>

int main ()
{
    using namespace std;
    const char* a = "Hello String!";
    cout << "a is: " << a << endl;

    std::string b(a); // constructor
    cout << "b is: " << b << endl;

    std::string c("Hello String!");
    std::string d = c;
    cout << "d is: " << d << endl;

    // Initialize a string to the first 5 characters of another
    std::string e(a, 5);
    cout << "e is: " << e << endl;

    // Initialize a string object to contain 10 'a's
    std::string f(10, 'a');
    cout << "f is: " << f << endl;

    return 0;
}

输出结果:

a is: Hello String!
b is: Hello String!
d is: Hello String!
e is: Hello
f is: aaaaaaaaaa
#include <iostream>
#include <string>

using namespace std;

int main()
{
    // 实例化并初始化string 对象时,无需关心字符串长度和内存分配细节。
    // STL string 类的构造函数将自动完成这些工作。
    std::string a = "hello, world";
    string b = a;
    std::string c (a, 3);
    // string d (10, "a");

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    cout << "c: " << c << endl;
    // cout << "d: " << d << endl;

    return 0;
}

2. 访问std::string 的字符内容

要访问 STL string 的字符内容,可使用迭代器,也可采用类似于数组的语法并使用下标运算符 [] 提供偏移量。要获得 string 对象的 C 风格表示,可使用成员函数 c_str()

#include <string>
#include <iostream>

int main ()
{
    using namespace std;
    string a ("Hello String"); // sample

    // Access the contents of the string using array syntax
    cout << "Display elements in string using array-syntax: " << endl;
    for (size_t i = 0; i < a.length(); ++i)
    {
        cout << "i [" << i << "] is: ";
        cout << a [i] << endl;
    }
    cout << endl;

    // Access the contents of a string using iterators
    cout << "Display elements in string using iterators: " << endl;
    int j = 0;
    string::const_iterator k;
    for (auto k = a.cbegin(); k != a.cend (); ++ k)
    {
        cout << "k [" << j ++ << "] is: ";
        cout << *k << endl;
    }
    cout << endl;

    // Access contents as a const char*
    cout << "The char* representation of the string is: ";
    cout << a.c_str () << endl;

    return 0;
}

3. 拼接字符串

要拼接字符串,可使用运算符 += ,也可使用成员函数 append()

#include <string>
#include <iostream>

using namespace std;

int main ()
{
    string a ("hello ");
    string b = "world";
    string c;
    c = a + b;

    string d;
    d.append(a);
    cout << "a is: " << a << endl;  // a is: hello 
    cout << "b is: " << b << endl;  // b is: world
    cout << "c is: " << c << endl;  // c is: hello world
    cout << "d is: " << d << endl;  // d is: hello 

    return 0;
}

4. 在 string 中查找字符或子字符串

STL string 类提供了成员函数 find() ,该函数有多个重载版本,可在给定 string 对象中查找字符或子字符串。

#include <string>
#include <iostream>
using namespace std;

int main ()
{
    string a ("Good day!");
    cout << "a is:" << a << endl;

    // Find substring "day" - find() returns position
    size_t charPos = a.find("day", 0);

    // Check if the substring was found...
    if (charPos != string::npos)
        cout << "First instance \"day\" at pos. " << charPos << endl;
    else
        cout << "Substring not found." << endl;

    cout << "Locating all instances of substring \"day\"" << endl;

    size_t subStrPos = a.find ("day", 0);
    while (subStrPos != string::npos)
    {
        cout << "\"day\" found at position " << subStrPos << endl;

        // Make find() search forward from the next character onwards
        size_t searchOffset = subStrPos + 1;

        subStrPos = a.find ("day", searchOffset);
    }

    return 0;
}

第 11~17 行演示了 find() 函数的最简单用法,它判断在 string 中是否找到了特定子字符串。这是通过将 find() 操作的结果与 std::string::npos (实际值为−1)进行比较实现的, std::string::npos 表明没有找到要搜索的元素。如果 find() 函数没有返回 npos ,它将返回一个偏移量,指出子字符串或字符在 string 中的位置。

这段代码演示了如何在 while 循环中使用 find() 函数在 STL string 查找指定字符或子字符串的所有实例。这里使用的 find 函数的重载版本接受两个参数:要搜索的子字符串或字符以及命令 find() 从哪里开始搜索的偏移量。在第 29 行,我们就通过指定偏移量,让 find() 搜索下一个指定的子字符串。

5. 字符串翻转

有时需要反转字符串的内容。假设要判断用户输入的字符串是否为回文,方法之一是将其反转,再与原来的字符串进行比较。反转 STL string 很容易,只需使用泛型算法 std::reverse()

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int main ()
{
    string a ("Hello String! We will reverse you!");
    cout << "The original sample string is: " << endl;
    cout << a << endl << endl;

    reverse (a.begin(), a.end());
    cout << "After applying the std::reverse algorithm: " << endl;
    cout << a << endl;

    return 0;
}

第 12 行的 std::reverse() 算法根据两个输入参数指定的边界反转边界内的内容。在这里,两个边界分别是 string 对象的开头和末尾,因此整个字符串都被反转。只要提供合适的输入参数,也可将字符串的一部分反转。注意,边界不能超过 end()

6. 字符串的大小写转换

要对字符串进行大小写转换,可使用算法 std::transform() ,它对集合中的每个元素执行一个用户指定的函数。在这里,集合是 string 对象本身。

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int main ()
{
    string a = "hello";
    transform(a.begin(), a.end(), a.begin(), ::toupper);
    cout << "The string converted to upper case is: " << endl;
    cout << a << endl << endl;

    transform(a.begin(), a.end(), a.begin(), ::tolower);
    cout << "The string converted to lower case is: " << endl;
    cout << a << endl << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wohu007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值