我想编写一个方法来修剪 std::string 的持续和尾随空格。例如,如果方法获得“HELLO WORLD”,它应该返回“HELLO WORLD”。注意,返回字符串之间是一个空格,这很重要。
这是我的方法的签名:
std::string MyHandler::Trim(const std::string& toTrim)
我的方法是将“toTrim”参数复制到非常量拷贝中。std::string toTrimCopy = toTrim;
现在我想获得一个非常量迭代器并在 for 循环中删除从开头和结尾的任何空格,而迭代器的值是一个空格。for (std::string::iterator it = toTrim.begin(); *it == ' '; it++)
{
toTrimCopy.erase(it);
}
for (std::string::iterator it = toTrim.end();
*it == ' ';
it--)
{
toTrimCopy.erase(it);
}
这会导致编译器错误:
StringHandling.C:60:49: error: conversion from ‘std::basic_string<char>::const_iterator {aka __gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >}’ to non-scalar type ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ requested
我来自 Java,现在学习 C++ 3 周。所以不要评判我。我怀疑
=
赋值将常量 char 指针分配给我的新字符串,因此我的拷贝是隐含的常量值。但我不完全知道。顺便说一句,这种方法也会引发异常:
std::string toTrimCopy = "";
std::strcpy(toTrimCopy, toTrim);
他说,他不能将字符串转换为 char 指针。
最佳答案
从 toTrim
传递迭代器是未定义的行为到 toTrimCopy
的方法,所以你很幸运类型不匹配捕获了它。std::string::begin
有两个重载:
std::string::iterator std::string::begin();
std::string::const_iterator std::string::begin() const;
const
字符串的 ness 参与重载决议。您不能初始化 iterator
来自 const_iterator
,因为这将允许您通过该迭代器修改基础对象。我会将您的功能更改为
namespace MyHandlerNS { // optional, could be in global namespace
std::string Trim(std::string toTrim) {
for (auto it = toTrim.begin(); it != toTrim.end() && *it == ' ';) {
it = toTrim.erase(it);
}
for (auto it = toTrim.rbegin(); it != toTrim.rend() && *it == ' ';) {
it = toTrim.erase(it.base());
}
return toTrim;
}
}
或者用标准算法完全摆脱循环#include <algorithm>
namespace MyHandlerNS { // optional, could be in global namespace
std::string Trim(std::string toTrim) {
auto isSpace = [](char c){ return c == ' '; };
auto it = std::find_if_not(toTrim.begin(), toTrim.end(), isSpace);
toTrim.erase(toTrim.begin(), it);
it = std::find_if_not(toTrim.rbegin(), toTrim.rend(), isSpace).base();
toTrim.erase(it, toTrim.end());
return toTrim;
}
}
关于c++ - `=` 分配给新的 std::string 究竟分配了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64459521/