C++字符串处理封装类String
概述
C++在处理字符串时相对于python等脚本语言并没有什么优势,下面将常用的字符串处理函数封装成一个String工具类,方便以后使用,后期还会对该类进行扩充,下面是具体的实现:
// String.hpp
#ifndef _STRING_HPP
#define _STRING_HPP
#include <string.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
class String
{
public:
static std::string trimLeft(const std::string& str, const std::string& token = " ")
{
std::string t = str;
t.erase(0, t.find_first_not_of(token));
return t;
}
static std::string trimRight(const std::string& str, const std::string& token = " ")
{
std::string t = str;
t.erase(t.find_last_not_of(token) + 1);
return t;
}
static std::string trim(const std::string& str, const std::string& token = " ")
{
std::string t = str;
t.erase(0, t.find_first_not_of(token));
t.erase(t.find_last_not_of(token) + 1);
return t;
}
static std::string toLower(const std::string& str)
{
std::string t = str;
std::transform(t.begin(), t.end(), t.begin(), tolower);
return t;
}
static std::string toUpper(const std::string& str)
{
std::string t = str;
std::transform(t.begin(), t.end(), t.begin(), toupper);
return t;
}
static bool startsWith(const std::string& str, const std::string& substr)
{
return str.find(substr) == 0;
}
static bool endsWith(const std::string& str, const std::string& substr)
{
return str.rfind(substr) == (str.length() - substr.length());
}
static bool equalsIgnoreCase(const std::string& str1, const std::string& str2)
{
return toLower(str1) == toLower(str2);
}
static std::vector<std::string> split(const std::string& str, const std::string& delimiter)
{
char* save = nullptr;
char* token = strtok_r(const_cast<char*>(str.c_str()), delimiter.c_str(), &save);
std::vector<std::string> result;
while (token != nullptr)
{
result.emplace_back(token);
token = strtok_r(nullptr, delimiter.c_str(), &save);
}
return result;
}
};
#endif
下面是String的具体使用例子:
// main.cpp
#include <iostream>
#include "String.hpp"
int main()
{
std::string str = "Hello world";
std::cout << String::trimLeft(str, "Hello") << std::endl;
std::cout << String::trimRight(str, "world") << std::endl;
str = " nihao ";
std::cout << String::trim(str) << std::endl;
std::cout << String::toUpper(str) << std::endl;
std::cout << String::toLower(String::toUpper(str)) << std::endl;
str = "Hello world";
std::cout << String::startsWith(str, "Hello") << std::endl;
std::cout << String::endsWith(str, "a") << std::endl;
std::vector<std::string> result = String::split(str, " ");
for (auto& iter : result)
{
std::cout << iter << std::endl;
}
return 0;
}
该例子的github地址:https://github.com/chxuan/samples/tree/master/String
兴趣是最好的老师,我的github地址:https://github.com/chxuan