簡體   English   中英

讀取字符串最后一行的最快方法?

[英]fastest way to read the last line of a string?

我想知道讀取std::string對象最后一行的最快方法。
從技術上講,以最快的方式最后一次出現\n之后的字符串?

這可以只使用string::find_last_ofstring::substr來完成,就像這樣

std::string get_last_line(const std::string &str)
{
  auto position = str.find_last_of('\n');
  if (position == std::string::npos)
    return str;
  else
    return str.substr(position + 1);
}

見:例子

我可能會使用std::string::rfindstd::string::substr並結合保證std::string::npos環繞以簡潔:

inline std::string last_line_of(std::string const& s)
{
    return s.substr(s.rfind('\n') + 1);
}

如果s.rfind('\n')沒有找到任何東西,它會返回std::string::npos C++標准說std::string::npos + 1 == 0 返回s.substr(0)總是安全的。

如果s.rfind('\n')確實找到了某些東西,那么您希望子字符串從下一個字符開始。 根據標准,再次返回s.substr(s.size())是安全的。

注意:C++17中,此方法將受益於有保證的返回值優化,因此它應該非常高效。

我想到了一種在存儲讀取內容的同時反向(向后)讀取字符串的方法

std::string get_last_line(const std::string &str)
{
    size_t l = str.length();
    std::string last_line_reversed, last_line;
    for (--l; l > 0; --l)
    {
        char c = str.at(l);
        if (c == '\n')
            break;
        last_line_reversed += c;
    }
    l = last_line_reversed.length();
    size_t i = 0, y = l;
    for (; i < l; ++i)
        last_line += last_line_reversed[--y];
    return last_line;
}

直到它遇到一個'\n'字符,然后將存儲的字符串反轉並返回它。 如果目標字符串很大並且有很多新行,這個函數會非常有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM