📜  c++中的子字符串函数(1)

📅  最后修改于: 2023-12-03 14:39:58.270000             🧑  作者: Mango

C++中的子字符串函数

在C++中,有许多用于操作字符串的函数,其中包括了一些用于处理子字符串的函数。在本篇文章中,我们将会介绍C++中的子字符串函数及其用法。

substr

substr函数用于从一个字符串中提取一个子字符串。该函数的原型如下:

string substr (size_t pos, size_t len) const;

其中,pos参数表示子字符串的起始位置,需要注意的是这里的pos从0开始计算;len参数表示子字符串的长度。

下面是一个示例程序:

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

int main() {
    string str = "Hello, World!";
    cout << "原始字符串:" << str << endl;
    string substr1 = str.substr(7, 5);
    string substr2 = str.substr(0, 5);
    cout << "第一个子字符串:" << substr1 << endl;
    cout << "第二个子字符串:" << substr2 << endl;
    return 0;
}

输出结果如下:

原始字符串:Hello, World!
第一个子字符串:World
第二个子字符串:Hello
find

find函数用于在一个字符串中查找指定字符串的位置。该函数的原型如下:

size_t find (const string& str, size_t pos = 0) const;

其中,str参数表示需要查找的字符串;pos参数表示查找的起始位置。

下面是一个示例程序:

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

int main() {
    string str = "Hello, World!";
    cout << "原始字符串:" << str << endl;
    size_t pos1 = str.find("World");
    size_t pos2 = str.find("Hello", 1);
    cout << "第一个子字符串的位置:" << pos1 << endl;
    cout << "第二个子字符串的位置:" << pos2 << endl;
    return 0;
}

输出结果如下:

原始字符串:Hello, World!
第一个子字符串的位置:7
第二个子字符串的位置:-1

其中,-1表示未找到指定字符串。

rfind

rfind函数同样用于在一个字符串中查找指定字符串的位置,与find函数不同的是,它从字符串的末尾开始查找字符串。该函数的原型和用法与find函数相同。

find_first_of

find_first_of函数用于在一个字符串中查找任意一个指定字符的位置。该函数的原型如下:

size_t find_first_of (const string& str, size_t pos = 0) const;

其中,str参数表示需要查找的字符集合;pos参数表示查找的起始位置。

下面是一个示例程序:

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

int main() {
    string str = "Hello, World!";
    cout << "原始字符串:" << str << endl;
    size_t pos1 = str.find_first_of("aeiou");
    size_t pos2 = str.find_first_of(",.;:-");
    cout << "元音字母的位置:" << pos1 << endl;
    cout << "标点符号的位置:" << pos2 << endl;
    return 0;
}

输出结果如下:

原始字符串:Hello, World!
元音字母的位置:1
标点符号的位置:5
find_last_of

find_last_of函数同样用于在一个字符串中查找任意一个指定字符的位置,与find_first_of函数不同的是,它从字符串的末尾开始查找字符。该函数的原型和用法与find_first_of函数相同。

总结

通过本篇文章的介绍,我们了解了C++中的几个常用的子字符串函数。这些函数可以方便地操作字符串,为我们的编程提供了很大的便利。