c++ get char of string
To get a character from a string in C++, you can use the indexing operator []
or the at()
function. Here is an example:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// Using the indexing operator []
char ch1 = str[0]; // Retrieves the first character 'H'
char ch2 = str[7]; // Retrieves the eighth character 'W'
// Using the at() function
char ch3 = str.at(4); // Retrieves the fifth character 'o'
char ch4 = str.at(11); // Retrieves the twelfth character 'd'
std::cout << ch1 << std::endl;
std::cout << ch2 << std::endl;
std::cout << ch3 << std::endl;
std::cout << ch4 << std::endl;
return 0;
}
In this example, we include the necessary header files iostream
and string
to use the std::string
class and the std::cout
object for output. We declare a std::string
variable str
and assign it the value "Hello, World!".
We then use the indexing operator []
to retrieve specific characters from the string. The index starts from 0, so str[0]
retrieves the first character 'H'
, and str[7]
retrieves the eighth character 'W'
.
Alternatively, we can use the at()
function of the std::string
class to achieve the same result. The at()
function takes an index as a parameter and returns the character at that index. In our example, str.at(4)
retrieves the fifth character 'o'
, and str.at(11)
retrieves the twelfth character 'd'
.
Finally, we use std::cout
to print each character to the console.
Note: It's important to ensure that the index used to access the character is within the bounds of the string. Otherwise, it may result in undefined behavior or an exception being thrown.