📅  最后修改于: 2023-12-03 15:35:09.347000             🧑  作者: Mango
std::string::find_last_of()
是一个C++标准库函数,用于在给定字符串中查找特定字符集中最后一个出现的字符,并返回其在字符串中的位置索引。该函数可以用于许多实际应用场景,例如在字符串中查找文件扩展名、路径名和HTTP URL参数等。
size_t find_last_of( const std::string& str, size_t pos = npos ) const;
find_last_of()
接受两个参数:
str
:一个字符串,表示要查找的字符集;pos
:一个可选的参数,表示开始查找的位置索引,默认值为npos
,即从字符串末尾开始查找。函数返回size_t
类型的值,表示字符集中最后一个出现的字符在字符串中的位置索引(从0开始);如果找不到该字符,则返回std::string::npos
。
下面是一个示例,演示如何使用std::string::find_last_of()
函数在给定字符串中查找文件路径中最后一个斜杠/
或反斜杠\
的位置。
#include <iostream>
#include <string>
int main() {
std::string file_path = "C:/Users/Administrator/Documents/example.txt";
size_t last_slash_idx = file_path.find_last_of("/\\");
if (last_slash_idx != std::string::npos) {
std::string file_name = file_path.substr(last_slash_idx + 1);
std::cout << "File name: " << file_name << std::endl;
}
return 0;
}
在上面的示例中,我们首先定义了一个字符串file_path
,表示文件的完整路径。然后,我们调用find_last_of()
函数查找路径中最后一个斜杠或反斜杠的位置索引,并将其存储在last_slash_idx
变量中。最后,我们使用substr()
函数从完整路径中提取文件名,并将其存储在file_name
变量中。
std::string::find_last_of()
的性能可能会受到许多因素的影响,例如字符串长度、字符集大小和搜索位置等。在实际应用中,我们应该尽量避免使用该函数在大型字符串中进行反复搜索,以确保程序的性能和效率。