簡體   English   中英

如何獲取std :: string的尾部?

[英]How to get the tail of a std::string?

如何檢索std::string的尾部?

如果願望成真,那就可以這樣:

string tailString = sourceString.right(6);

但這似乎太容易了,而且不起作用......

有什么好的解決方案?

可選問題:如何使用Boost字符串算法庫?

添加:

即使原始字符串小於6個字符,該方法也應該保存。

有一點值得注意:如果使用超出數組末尾的位置調用substr (優於大小),則拋出out_of_range異常。

因此:

std::string tail(std::string const& source, size_t const length) {
  if (length >= source.size()) { return source; }
  return source.substr(source.size() - length);
} // tail

您可以將其用作:

std::string t = tail(source, 6);

使用substr()方法和字符串的size() ,只需獲取它的最后一部分:

string tail = source.substr(source.size() - 6);

對於處理小於尾部大小的字符串的情況,請參閱Benoit的答案 (並且贊成它,我不明白為什么我得到7個upvotes而Benoit提供更完整的答案!)

你可以這樣做:

std::string tailString = sourceString.substr((sourceString.length() >= 6 ? sourceString.length()-6 : 0), std::string::npos);

請注意, npos是默認參數,可能會被省略。 如果您的字符串的大小超過6,則此例程將提取整個字符串。

這應該這樣做:

string str("This is a test");
string sub = str.substr(std::max<int>(str.size()-6,0), str.size());

甚至更短,因為subst的字符串結束為第二個參數的默認值:

string str("This is a test");
string sub = str.substr(std::max<int>(str.size()-6,0));

您可以使用迭代器來執行此操作:

   #include <iostream>
   #include <string>
   using namespace std;

   int main () 
   {
        char *line = "short line for testing";
        // 1 - start iterator
        // 2 - end iterator
        string temp(line);

        if (temp.length() >= 8) { // probably want at least one or two chars
        // otherwise exception is thrown
            int cut_len = temp.length()-6;
            string cut (temp.begin()+cut_len,temp.end());
            cout << "cut  is: " << cut << endl;
        } else {
            cout << "Nothing to cut!" << endl;
        }
        return 0;
    }

輸出:

cut  is: esting

由於您還要求使用boost庫的解決方案:

#include "boost/algorithm/string/find.hpp"

std::string tail(std::string const& source, size_t const length) 
{
    boost::iterator_range<std::string::const_iterator> tailIt = boost::algorithm::find_tail(source, length);
    return std::string(tailIt.begin(), tailIt.end());
} 

請嘗試以下方法:

std::string tail(&source[(source.length() > 6) ? (source.length() - 6) : 0]);
string tail = source.substr(source.size() - min(6, source.size()));

嘗試使用substr方法。

我認為,使用迭代器是C ++方式

像這樣的東西:

#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

std::string tail(const std::string& str, size_t length){
    string s_tail;
    if(length < str.size()){
        std::reverse_copy(str.rbegin(), str.rbegin() + length, std::back_inserter(s_tail));
    }
    return s_tail;
}


int main(int argc, char* argv[]) {
    std::string s("mystring");
    std::string s_tail = tail(s, 6);
    cout << s_tail << endl;
    s_tail = tail(s, 10);
    cout << s_tail << endl;
    return 0;
}

暫無
暫無

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

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