C++ 获取 std::string 的最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4884548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:50:27  来源:igfitidea点击:

Get the last element of a std::string

c++string

提问by Deve

I was wondering if there's an abbreviation or a more elegant way of getting the last character of a string like in:

我想知道是否有缩写或更优雅的方式来获取字符串的最后一个字符,例如:

char lastChar = myString.at( myString.length() - 1 );

Something like myString.back()doesn't seem to exist. Is there an equivalent?

类似的东西myString.back()似乎不存在。有等价物吗?

回答by templatetypedef

In C++11 and beyond, you can use the backmember function:

在 C++11 及更高版本中,您可以使用back成员函数:

char ch = myStr.back();

In C++03, std::string::backis not available due to an oversight, but you can get around this by dereferencing the reverse_iteratoryou get back from rbegin:

在 C++03 中,std::string::back由于疏忽而不可用,但您可以通过取消引用reverse_iterator您从rbegin以下位置返回的来解决此问题:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

在这两种情况下,请注意确保字符串中至少包含一个字符!否则,你会得到undefined behavior,这是一件坏事。

Hope this helps!

希望这可以帮助!

回答by Kerri Brown

You probably want to check the length of the string first and do something like this:

您可能想先检查字符串的长度并执行如下操作:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}

回答by fredoverflow

You could write a function template backthat delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:

您可以编写一个函数模板back,委托给普通容器的成员函数和一个实现字符串缺失功能的普通函数:

template <typename C>
typename C::reference back(C& container)
{
    return container.back();
}

template <typename C>
typename C::const_reference back(const C& container)
{
    return container.back();
}

char& back(std::string& str)
{
    return *(str.end() - 1);
}

char back(const std::string& str)
{
    return *(str.end() - 1);
}

Then you can just say back(foo)without worrying whether foois a string or a vector.

然后你可以直接说back(foo)而不用担心foo是字符串还是向量。

回答by tenpn

*(myString.end() - 1)maybe? That's not exactly elegant either.

*(myString.end() - 1)也许?这也不是很优雅。

A python-esque myString.at(-1)would be asking too much of an already-bloated class.

python-esquemyString.at(-1)会要求太多已经臃肿的类。