#include<string> namespace cutl { /** * @brief Remove leading whitespaces from a string. * * @param str the string to be stripped. * @return std::string the stripped string. */ std::string lstrip(const std::string &str); /** * @brief Remove trailing whitespaces from a string. * * @param str the string to be stripped. * @return std::string the stripped string. */ std::string rstrip(const std::string &str); /** * @brief Remove leading and trailing whitespaces from a string. * * @param str the string to be stripped. * @return std::string the stripped string. */ std::string strip(const std::string &str); } // namespace cutl
size_t index = 0; for (size_t i = 0; i < str.length(); i++) { if (!std::isspace(str[i])) { index = i; break; } }
return str.substr(index, str.length() - index); }
std::string rstrip(const std::string &str) { if (str.empty()) { return""; }
size_t index = str.length() - 1; for (size_t i = str.length() - 1; i >= 0; i--) { if (!std::isspace(str[i])) { index = i; break; } } return str.substr(0, index + 1); }
std::string strip(const std::string &str) { if (str.empty()) { return""; }
size_t index1 = 0; for (size_t i = 0; i < str.length(); i++) { if (!std::isspace(str[i])) { index1 = i; break; } } size_t index2 = str.length() - 1; for (size_t i = str.length() - 1; i >= 0; i--) { if (!std::isspace(str[i])) { index2 = i; break; } } auto len = index2 - index1 + 1;
std::string text = " \tThis is a test string. \n "; // std::string text = " \t中国 \n "; std::cout << "text: " << text << std::endl; std::cout << "trim left text: " << cutl::lstrip(text) << std::endl; std::cout << "trim right text: " << cutl::rstrip(text) << std::endl; std::cout << "trim text: " << cutl::strip(text) << std::endl; }
5. 运行结果
1 2 3 4 5 6 7
---------------------------------------------TestStrip---------------------------------------------- text: This is a test string. trim left text: This is a test string. trim right text: This is a test string. trim text: This is a test string.