C++ 如何在C++中获取字符串的最后一个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32391036/
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
How to get last character of string in c++?
提问by Hamza Tahboub
In python you can say print "String"[-1]
and it would print be the last character, 'g'. Is there an equivalent for this in c++?
在 python 中,你可以说它print "String"[-1]
会打印最后一个字符,'g'。在 C++ 中是否有这样的等价物?
回答by David Schwartz
You can use string.back()to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string.rbegin()will give you an iterator to the last character.
您可以使用string.back()获取对字符串中最后一个字符的引用。字符串的最后一个字符是反转字符串中的第一个字符,因此string.rbegin()将为您提供一个指向最后一个字符的迭代器。
回答by Tim Biegeleisen
Use the back()
function for std::string
:
将该back()
函数用于std::string
:
std::string str ("Some string");
cout << str.back()
Output:
输出:
g
回答by Shreevardhan
For C strings, it is
对于 C 字符串,它是
String[strlen(String) - 1];
For C++ style strings, it is either
对于 C++ 风格的字符串,它要么是
String.back();
*String.rbegin();
String[String.length() - 1];
回答by pzelasko
You can use the function:
您可以使用该功能:
my_string.back();
If you want to output it, then:
如果你想输出它,那么:
#include <iostream>
std::cout << my_string.back();