std::string::at can be used to extract characters by characters from a given string.
It supports two different syntaxes both having similar parameters:
Syntax 1:
char& string::at (size_type idx)
Syntax 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.
Output:
F
Application
std::string::at can be used for extracting characters from string. Here is the simple code for the same.
CPP
#include <iostream>
using namespace std;
void extractChar(string str)
{
char ch;
int l = str.length();
for ( int i = 0; i < l; i++) {
ch = str.at(i);
cout << ch << " " ;
}
}
int main()
{
string str( "GeeksForGeeks" );
extractChar(str);
return 0;
}
|
Output:
G e e k s F o r G e e k s
Last Updated :
08 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...