std :: 字符串 :: 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.
Return value : Returns character at the specified position in the string.
Exception : 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
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
应用
std :: 字符串 :: at可用于从字符串提取字符。这是相同的简单代码。
// CPP code to extract characters from a given string
#include
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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。