本文主要是介绍C++ 字符串处理-去除字符串前后的空字符,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 1. 关键词
- 2. strutil.h
- 3. strutil.cpp
- 4. 测试代码
- 5. 运行结果
- 6. 源码地址
1. 关键词
C++ 字符串处理 去除字符串前后的空字符 跨平台
2. strutil.h
#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
3. strutil.cpp
#include <cctype>
#include <algorithm>
#include "strutil.h"namespace cutl
{std::string lstrip(const std::string &str){if (str.empty()){return "";}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;return str.substr(index1, len);}
} // namespace cutl
4. 测试代码
#include "common.hpp"
#include "strutil.h"void TestStrip()
{PrintSubTitle("TestStrip");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. 运行结果
---------------------------------------------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.
6. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。
这篇关于C++ 字符串处理-去除字符串前后的空字符的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!