HOWTO · C++

如何在 C++ 中從字串取得最後一個字元

本文討論從 C++ 中的字串中獲取最後一個字元。

本頁內容

對於 "Spider Man" 這樣的字串,text.back() 直接參照其最後一個字元。當您想要經過檢查的位置存取時,也可以使用 at(text.size() - 1)。在使用這些方法中的任何一種之前,字串必須包含一個字元。

在 C++ 中使用 std::string::at 從字串中獲取最後一個字元

std::string::at(index) 傳回從零開始的位置處的字元,並檢查該位置是否在字串內。最後一個位置是 text.size() - 1。如果索引在字串之外,at() 會擲出 std::out_of_range;索引類型是無符號的,因此負值會轉換為一個較大的無符號值,而不是作為有效的負索引。

執行此範例:

#include <iostream>
#include <string>

int main() {
    const std::string text = "Spider Man";
    std::cout << "Character at position 3: " << text.at(3) << '\n';
    std::cout << "Character at last position: "
              << text.at(text.size() - 1) << '\n';
}

第一次存取使用索引 3;第二次根據字串長度計算最後一個索引。在計算和使用該最後位置之前,請檢查字串不為空。

在 C++ 中使用 std::string::back() 從字串中獲取最後一個字元

std::string::back() 是存取最後一個字元的直接方式。它傳回一個參照,因此您可以透過該參照讀取字元或賦予取代值。在空字串上呼叫 back() 是未定義行為,因此在使用前請檢查字串。

#include <iostream>
#include <string>

int main() {
    std::string text = "Spider Man";
    const char last = text.back();
    std::cout << "Character at the end: " << last << '\n';
    text.back() = '@';
    std::cout << "After replacement: " << text << '\n';
}

第一次呼叫讀取 n;賦值將字串更改為 "Spider Ma@"。

在 C++ 中使用 std::string::rbegin() 從字串中獲取最後一個字元

std::string::rbegin() 傳回一個反向迭代器,其第一個位置對應於字串的最後一個字元。只要字串不為空,解參照它即可讀取該字元。

#include <iostream>
#include <string>

int main() {
    const std::string text = "Spider Man";
    const auto last = *text.rbegin();
    std::cout << "The last character is: " << last << '\n';
}

在進行反向迭代時使用 rbegin();對於單個字元,back() 更直接。

在 C++ 中使用 std::reverse 和字串迭代器取得最後一個字元

std::reverse 是在 <algorithm> 中宣告的演算法,而不是 std::string 成員函式。它就地反轉迭代器範圍內的元素。反轉非空字串後,text.front() 參照原來位於最後的字元。這會更改整個字串,因此當您只需要讀取其最後一個字元時,通常沒有必要這樣做。

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string text = "Spider Man";
    std::reverse(text.begin(), text.end());
    std::cout << "The former last character is: " << text.front() << '\n';
}

該演算法在從 begin() 到 end() 的半開區間上運行。在之後讀取 front() 之前,請確保字串不為空。

在 C++ 中使用 std::string::substr() 從字串中獲取最後一個字元

std::string::substr(position, count) 傳回一個新字串。對於至少包含一個字元的字串,text.substr(text.size() - 1, 1) 將其最後一個字元擷取為一個單字元字串。在計算起始位置之前,請檢查是否存在字元。

#include <iostream>
#include <string>

int main() {
    const std::string text = "Spider Man";
    const std::string last = text.substr(text.size() - 1, 1);
    std::cout << "Last character extracted: " << last << '\n';
}

當結果應該是字串時選擇 substr();當 char 足夠時使用字元存取操作。

在 C++ 中使用陣列索引存取字串的字元

std::string 支援 operator[],因此在確認字串不為空後,最後一個字元可以讀取為 text[text.size() - 1]。與 at() 不同,operator[] 對於超出範圍的位置不提供相同的經過檢查的存取。

#include <iostream>
#include <string>

int main() {
    const std::string text = "Spider Man";
    std::cout << "The last character is: "
              << text[text.size() - 1] << '\n';
}

索引從零開始:對於長度為 n 的字串,最後一個字元位於索引 n - 1 處。如果您希望透過例外報告超出範圍的索引,請優先使用 at()。

結論

要直接存取非空 std::string 的最後一個字元,請使用 back()。當經過檢查的位置存取有用時,選擇 at(size() - 1)。rbegin() 也透過反向迭代到達最後一個字元,substr() 將其作為字串傳回,而索引使用相同的最後位置,但沒有 at() 的邊界檢查。在存取字串結尾之前,請檢查字串包含一個字元。