c++ - 获取字符串的最后一行

标签 c++ string

我目前已经实现了这个逻辑来从字符串中获取最后一行。我确信这不是有效的解决方案。

...
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/

相关文章:

c++ - *(1 + &foo) 与 C/C++ 中的 *(&foo + 1) 相同吗?

c++ - std::find 的奇怪行为,当元素不在 vector 中时返回 true

c - 使用 sscanf 从文件中读取

javascript - 确认字符串的结尾(可变结尾长度)

r - 在 R 中修剪长字符向量的更快方法

c++ - 从 N 个元素的元组到 N/2 对的元组

c++ - 读取注册表值 32 位?

c++ - 将对数组的引用传递给返回数组引用的函数

ios - 快速将 double 组转换为 UIImage

c - 替换字符串中的字符