C++ 如何获取std::string的尾部?

C++ 如何获取std::string的尾部?,c++,C++,如何检索std::string的尾部 如果愿望能够实现,它将是这样的: string tailString = sourceString.right(6); #include <string> #include <iostream> #include <algorithm> #include <iterator> using namespace std; std::string tail(const std::string& str,

如何检索
std::string
的尾部

如果愿望能够实现,它将是这样的:

string tailString = sourceString.right(6);
#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;
}
但这似乎太容易了,而且不起作用

有好的解决方案吗

可选问题:如何使用Boost字符串算法库

添加:

即使原始字符串小于6个字符,也应保存该方法。

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

string tail = source.substr(source.size() - 6);
对于处理小于尾部大小的字符串的情况,请参见(并向上投票,我不明白为什么我得到7次向上投票,而Benoit提供了更完整的答案!)

您可以执行以下操作:

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

请注意,
npos
是默认参数,可以省略。如果字符串的大小超过6,则此例程将提取整个字符串。

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

   #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;
    }

尝试方法。

有一个警告需要注意:如果调用的位置超过数组的末尾(大于大小),则会引发
超出范围的异常

因此:

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);

我认为,使用迭代器是C++方式< /P> 诸如此类:

string tailString = sourceString.right(6);
#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
标准::字符串尾(常量标准::字符串和字符串,大小和长度){
串尾;
如果(长度
string str("This is a test");
string sub = str.substr(std::max<int>(str.size()-6,0), str.size());
string str(“这是一个测试”);
string sub=str.substr(std::max(str.size()-6,0),str.size());
甚至更短,因为subst将字符串end作为第二个参数的默认值:

string str("This is a test");
string sub = str.substr(std::max<int>(str.size()-6,0));
string str(“这是一个测试”);
string sub=str.substr(std::max(str.size()-6,0));

由于您还要求使用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());
} 
#包括“boost/algorithm/string/find.hpp”
标准::字符串尾部(标准::字符串常量和源,大小常量长度)
{
boost::iterator_range tailIt=boost::algorithm::find_tail(源,长度);
返回std::string(tailIt.begin(),tailIt.end());
} 
尝试以下操作:

std::string tail(&source[(source.length() > 6) ? (source.length() - 6) : 0]);


一个问题:你想要最后6个字符还是除了前6个字符以外的所有字符?不清楚…我想要最后6个字符。下面所有答案之后还有一个问题:为什么string类没有成员方法
right(size\t)这会使C++程序员的生活变得更容易。如果有少于六个字符,它应该怎么做?返回原样字符串吗?返回空字符串。返回字符串填充到六个字符?@ RalaldMcBeNe:不是。事实是,<代码>字符串< /Cord>类已经有太多的功能(对偶索引/迭代器…).标准库并不意味着为每个数据结构提供所有可能有用的功能(这太疯狂了),它提供了核心功能,允许用户根据自己的需要扩展行为。坦率地说:我以前从未需要您的精确要求:)这是返回字符串的开头,不是吗?这对小于所需6个字符的字符串有效吗?@Charles:默认情况下
substr
运行到字符串结尾,因此第二个
6
是多余的。@RonaldMcBean:不,它不是。将引发异常。不,Benoit的答案更好。如果大小更小,您将得到内存访问失败think@RonaldMcBean—您只需添加一个简单的测试来检查字符串长度。第一个版本不会处理您认为的情况
std::string::size\u type
很可能是无符号的,
source.length()
将在下溢时简单地“环绕”,结果将是
std::numeric\u limits::max()-6+source.length()
,远大于
0
。第二种方法是正确的。这不是更好:'substr(min(sourceString.length()-6,0),std::string::npos)“?但我想这是口味的问题。@Ronald McBean:不,因为sourceString.length()是无符号的(
size\u type
)因此,当你减去6时,你可能会得到意想不到的结果。@RonaldMcBean:对无符号类型使用
min
0
,结果是可以预测的:一个更安全的解决方案可能是:
返回std::string(source.end()-std::min(n,source.size()),source.end();
(但原始版本也很好)欢迎使用Stack Overflow!虽然这在理论上可以回答这个问题,但请在此处包含答案的基本部分,并提供链接供参考。+1回答不错。应该接受回答IMHO。你可以说这很优雅。+1回答我的问题很好。它是可读的代码,完全符合我的要求。@Ronald McBean:Rememb呃..如果这符合您的意图,请不要忘记选中accept。@RonaldMcBean:从我这里开始,这是更好的且可测试的。您还可以很容易地将其作为模板来操作任何
基本字符串
,或者通过一个双向迭代器和一个接受
(迭代器,迭代器)的构造函数来操作任何范围
。如果源字符串小于6个字符怎么办?而且,这看起来非常复杂。@Ronald当然,你应该在之前检查长度。编辑以使示例更清楚。我不这么认为,这只是一种标准的库用法。@YuriS.Cherkasov:
substr
更容易,而且可能更快,因为它需要复制一个字符串e一下子,当你一个字符一个字符地复制时。@MatthieuM。不一定,如果迭代器指向一个连续的范围,复制可以得到优化。如果大小太大而不能保持在
int
(我知道,这不太可能)。为了完整性,你可能需要解释一下你的代码在做什么。