此函數返回對字符串最後一個字符的直接引用。這隻能用於非空字符串。
這可以用來訪問字符串的最後一個字符,也可以在字符串的末尾附加一個字符。追加字符後,字符串的長度保持不變,字符串的最後一個字符被新的替換
用法
string str ("GeeksforGeeks"); Accessing last character char end_char = str.back(); Appending character at end of string str.back() = '#';
參數:該函數不帶參數
返回值:對字符串中最後一個字符的引用
異常:如果字符串為空,則顯示未定義的行為。
以下示例說明了上述方法的用法:
程序1:
// C++ program to demonstrate
// the use of the above method
#include <iostream>
// for std::string::back
#include <string>
using namespace std;
int main()
{
string str("GeeksforGeeks");
// Accessing last character of string
char end_char = str.back();
cout << "Last character of string = "
<< end_char << endl;
// Appending a character to
// the end of string
str.back() = '#';
cout << "New string = " << str << endl;
return 0;
}
輸出:
Last character of string = s New string = GeeksforGeek#
程序2:當字符串為空時,它將顯示未定義的行為。
// C++ program to demonstrate
// the use of the above method
#include <iostream>
// for std::string::front
#include <string>
using namespace std;
int main()
{
string str(""); // Empty string
// trying to access last character
// of an empty string
char end_char = str.back();
cout << "Last character of string = "
<< end_char << endl;
// Appending a character to
// the end of an empty string
str.back() = '#';
cout << "New string = " << str << endl;
return 0;
}
輸出:
Last character of string = New string = ÉGà @ ·ùþ?aPé£Îý @ ?k¯Ã ÿÿÿÿÿÿÿXé£Îý ÿÿÿ @ Ï?¨Õ,Ä @ Pé£Îý Ï??Á±?ðÏ?Ø%Bð 3ÇGà ¸ÂEà :µ# @ Pé£Îý I@ Hé£Îý ªÿ£Îý ! P·Îý ÿû? d @ @ 8 ÀFà @ é é é é ©ê£Îý Ñÿ£Îý ¹ê£Îý ¾·ùþ?aDdCâ?gCx86_64
相關用法
- C++ cin get()用法及代碼示例
- C++ set_symmetric_difference用法及代碼示例
- C++ ios bad()用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ std::mismatch()用法及代碼示例
- C++ cauchy_distribution a()用法及代碼示例
注:本文由純淨天空篩選整理自sanjeev2552大神的英文原創作品 std::string::back() in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。