std::string::at可用於從給定字符串中按字符提取字符。
它支持兩種具有相似參數的不同語法:
語法1:
char& string::at (size_type idx)
語法2:
const char& string::at (size_type idx) const idx: index number Both forms return the character that has the index idx (the first character has index 0). For all strings, an index greater than or equal to length() as value is invalid. If the caller ensures that the index is valid, she can use operator [], which is faster. 返回值:Returns character at the specified position in the string. 異常:Passing an invalid index (less than 0 or greater than or equal to size()) throws an out_of_range exception.
// CPP code to demonstrate std::string::at
#include <iostream>
using namespace std;
// Function to demonstarte std::string::at
void atDemo(string str)
{
cout << str.at(5);
// Below line throws out of
// range exception as 16 > length()
// cout << str.at(16);
}
// Driver code
int main()
{
string str("GeeksForGeeks");
atDemo(str);
return 0;
}
輸出:
F
Application
std::string::at可用於從字符串中提取字符。這是相同的簡單代碼。
// CPP code to extract characters from a given string
#include <iostream>
using namespace std;
// Function to demonstarte std::string::at
void extractChar(string str)
{
char ch;
// Calculating the length of string
int l = str.length();
for (int i = 0; i < l; i++) {
ch = str.at(i);
cout << ch << " ";
}
}
// Driver code
int main()
{
string str("GeeksForGeeks");
extractChar(str);
return 0;
}
輸出:
G e e k s F o r G e e k s
相關用法
- C++ std::string::insert()用法及代碼示例
- C++ std::string::data()用法及代碼示例
- C++ std::string::compare()用法及代碼示例
- C++ std::string::find_first_not_of用法及代碼示例
- C++ getline(string)用法及代碼示例
- C++ std::string::append()用法及代碼示例
- C++ std::string::assign()用法及代碼示例
- C++ std::string::push_back()用法及代碼示例
注:本文由純淨天空篩選整理自 string at() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。