我目前已经实现了这个逻辑来从字符串中获取最后一行。我确信这不是有效的解决方案。
...
string response;
while (1) {
string newResponse = SocketRead();
response += newResponse;
if(checkIfReceiveComplete(response)) {
break;
}
}
...
bool checkIfReceiveComplete(string &response) {
size_t index = response.find_last_of("\r\n");
if (response+ 1 == response.length()) {
response.pop_back();
response.pop_back();
index = response.find_last_of("\r\n");
}
string lastLine = response.substr(index + 1);
return (lastLine.find(" OK ") != string::npos);
}
请让我知道如何高效地实现这一点。
注意:我没有从文件中读取。所以我不确定是否可以使用seekg()。
最佳答案
std::string
内部存储了一个char*
,它在空间上是连续的,因此易于访问。我们可以使用它从后面搜索最后一个(或倒数第二个)返回字符:
inline bool is_return(const char& input)
{
return input == '\n' || input == '\r';
}
string last_line (const string& input)
{
if(input.length() == 1) return input;
size_t position = input.length()-2; // last character might be a return character, we can jump over it anyway
while((not is_return(input[position])) and position > 0) position--;
// now we are at the \n just before the last line, or at the first character of the string
if(is_return(input[position])) position += 1;
// now we are at the beginning of the last line
return input.substr(position);
}
此代码假设输入确实很大,而输出(/最后一行的大小)则不然。不使用任何特殊的 STL 函数,可能有一些不错的技巧,但应该可行。
一项改进可能是在位置递减时提前访问某些 block ,以便将多个数据 block 预加载到缓存中。不确定这是如何理想地完成的,如果这有很大的影响或者甚至是必要的,也许其他人可以详细说明。如果最后一行很小的假设成立,则没有必要。
关于c++ - 获取字符串的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54980425/