乐闻世界logo
搜索文章和话题

Get the last element of a std:: string

1个答案

1

In C++, retrieving the last character of std::string can be achieved in multiple ways. The following are several common methods:

Method 1: Using the Subscript Operator

If the string is non-empty, you can directly access the last character using the subscript operator []:

cpp
std::string str = "Hello, World!"; char lastChar = str[str.length() - 1];

Here, str.length() - 1 provides the index of the last character.

Method 2: Using the at() Member Function

The at() function provides bounds checking. If the index is out of bounds, it throws a std::out_of_range exception. This makes using the at() method safer than using the subscript operator directly:

cpp
std::string str = "Hello, World!"; try { char lastChar = str.at(str.length() - 1); } catch (std::out_of_range& e) { std::cerr << "Out of range error: " << e.what() << '\n'; }

Method 3: Using the back() Member Function

Since C++11, std::string provides the back() function, which directly returns the last character of the string. It is convenient and concise:

cpp
std::string str = "Hello, World!"; char lastChar = str.back(); // Directly retrieves the last character

The back() function assumes the string is not empty; calling it on an empty string may result in undefined behavior.

Method 4: Using Iterators

You can also access the last character using iterators, which provides a consistent interface when working with strings and other containers:

cpp
std::string str = "Hello, World!"; if (!str.empty()) { auto lastChar = *(str.end() - 1); }

Here, str.end() returns an iterator pointing to the end of the string (the position after the last character), so subtracting 1 gives the iterator for the last character.

Example Usage

Suppose we need to write a function that prints the last character of a provided std::string (if the string is not empty):

cpp
void printLastCharacter(const std::string& str) { if (!str.empty()) { char lastChar = str.back(); // Using the back() function to retrieve the last character std::cout << "The last character is: " << lastChar << std::endl; } else { std::cout << "The string is empty." << std::endl; } } // Example call int main() { std::string testStr = "Hello, World!"; printLastCharacter(testStr); return 0; }

These methods demonstrate how to safely and efficiently retrieve the last character of std::string in practical applications.

2024年6月29日 12:07 回复

你的答案