1. 关键词
C++ 字符串处理 starts_with ends_with std::string 跨平台
2. C++20及之后
C++20标准开始,STL已经提供了starts_with
和ends_with
函数,可以直接使用。在 <string>
头文件中,可以直接作为字符串对象的成员函数使用。
官方API文档: https://en.cppreference.com/w/cpp/string/basic_string
3. C++20之前
C++20之前, STL本身不支持starts_with和ends_with的功能,开发者需要自己实现,可参考以下实现代码。
3.1. strutil.h
#include <string>
namespace cutl
{
/**
* @brief Check if a string starts with a given substring.
*
* @param str the string to be checked.
* @param start the substring to be checked.
* @param ignoreCase whether to ignore case when comparing, default is false.
* @return true if the string starts with the substring, false otherwise.
*/
bool starts_with(const std::string &str, const std::string &start, bool ignoreCase = false);
/**
* @brief Check if a string ends with a given substring.
*
* @param str the string to be checked.
* @param end the substring to be checked.
* @param ignoreCase whether to ignore case when comparing, default is false.
* @return true if the string ends with the substring, false otherwise.
*/
bool ends_with(const std::string &str, const std::string &end, bool ignoreCase = false);
} // namespace cutl
3.2. strutil.cpp
#include <cctype>
#include <algorithm>
#include "strutil.h"
namespace cutl
{
bool starts_with(const std::string &str, const std::string &start, bool ignoreCase)
{
int srclen = str.size();
int startlen = start.size();
if (srclen < startlen)
{
return false;
}
std::string temp = str.substr(0, startlen);
if (ignoreCase)
{
return to_lower(temp) == to_lower(start);
}
else
{
return temp == start;
}
}
bool ends_with(const std::string &str, const std::string &end, bool ignoreCase)
{
int srclen = str.size();
int endlen = end.size();
if (srclen < endlen)
{
return false;
}
std::string temp = str.substr(srclen - endlen, endlen);
if (ignoreCase)
{
return to_lower(temp) == to_lower(end);
}
else
{
return temp == end;
}
}
} // namespace cutl
3.3. 测试代码
#include "common.hpp"
#include "strutil.h"
void TestStartswithEndswith()
{
PrintSubTitle("TestStartswithEndswith");
std::string str1 = "Hello, world!";
std::string str2 = "GOODBYE, WORLD!";
std::cout << str1 << " start with hello : " << cutl::starts_with(str1, "hello") << std::endl;
std::cout << str1 << " start with hello ignoreCase: " << cutl::starts_with(str1, "hello", true) << std::endl;
std::cout << str2 << " end with world! : " << cutl::ends_with(str2, "world!") << std::endl;
std::cout << str2 << " end with world! ignoreCase: " << cutl::ends_with(str2, "world!", true) << std::endl;
}
3.4. 运行结果
---------------------------------------TestStartswithEndswith---------------------------------------
Hello, world! start with hello : 0
Hello, world! start with hello ignoreCase: 1
GOODBYE, WORLD! end with world! : 0
GOODBYE, WORLD! end with world! ignoreCase: 1
3.5. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。