带有测试的解决方案
有点令人惊讶的是,这里的回答中没有提供一个测试函数来演示在边界情况下trim
的行为。空字符串和完全由空格组成的字符串都可能会引起问题。
以下是这样一个函数:
#include <iomanip>
#include <iostream>
#include <string>
void test(std::string const& s)
{
auto const quote{ '\"' };
auto const q{ quote + s + quote };
auto const t{ quote + trim(s) + quote };
std::streamsize const w{ 6 };
std::cout << std::left
<< "s = " << std::setw(w) << q
<< " : trim(s) = " << std::setw(w) << t
<< '\n';
}
int main()
{
for (std::string s : {"", " ", " ", "a", " a", "a ", " a "})
test(s);
}
测试接受的解决方案
当我在2023年8月5日运行这个接受的答案时,对它处理完全由空格组成的字符串感到失望。我期望它们被修剪为空字符串。相反,它们保持不变地返回了。这是if语句的原因。
using namespace std;
string trim(const string& str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
这是我的测试输出结果:
s = "" : trim(s) = ""
s = " " : trim(s) = " "
s = " " : trim(s) = " "
s = "a" : trim(s) = "a"
s = " a" : trim(s) = "a"
s = "a " : trim(s) = "a"
s = " a " : trim(s) = "a"
测试“新的改进版”修剪功能
为了使其按照我想要的方式工作,我改变了if语句。
趁机还把using namespace std;
删掉了,并将参数名称改为s
。你知道的,因为我可以这样做。
std::string trim(std::string const& s)
{
auto const first{ s.find_first_not_of(' ') };
if (first == std::string::npos)
return {};
auto const last{ s.find_last_not_of(' ') };
return s.substr(first, (last - first + 1));
}
现在测试程序产生了我喜欢的输出结果。
s = "" : trim(s) = ""
s = " " : trim(s) = ""
s = " " : trim(s) = ""
s = "a" : trim(s) = "a"
s = " a" : trim(s) = "a"
s = "a " : trim(s) = "a"
s = " a " : trim(s) = "a"
song
是一个命名空间吗?还是一个类? - K-ballo