我正在尝试使用C ++查找
采用字符串和整数的代码,对于给定的分隔符,假设为“。”,则从最后一个子字符串到第n个结果。
示例 输入:
字符串“ a.b.c.d.e”和delimFromEndLevel = 1 =>字符串“ a.b.c.d”
字符串“ a.b.c.d.e”和delimFromEndLevel = 2 =>字符串“ a.b.c”
等
起点是以下代码:
void elaborateParent( const std::string& input, unsigned int levels )
{
std::size_t cutOffIndex = std::string::npos;
while (levels > 0)
{
cutOffIndex = input.rfind('.', cutOffIndex);
if (cutOffIndex == std::string::npos)
std::cout << "Not enough levels to go up!" << std::endl;
levels--;
if (levels>0)
{
if (cutOffIndex>0)
cutOffIndex--;
else
std::cout << "Not enough levels to go up!" << std::endl;
}
}
std::string result = input.substr(0, cutOffIndex);
std::cout << "Elaboration parent result: '" << result << "'" << std::endl;
}
答案 0 :(得分:0)
您过于复杂了:)
只需:
std::string elaborateParent( const std::string& input, unsigned int levels )
{
auto result = input;
for(; levels != -1; --levels) {
result.erase(result.find_last_of('.'));
}
return result;
}
我怀疑您的性能会比此更好!