How to Access Individual Characters in a C++ String?
Last Updated :
21 Feb, 2024
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. In this article, we are going to learn how to access individual characters in a C++ String.
Example
Input:
myString = "GeeksforGeeks";
Output:
4th Character = k
Access Individual Characters in a C++ String
In C++, you can access individual characters in a std::string using the array subscript [] operator. We need to just pass the index between the [] operator. Indexing of string starts with 0.
C++ Program to Access Individual Characters in a String
C++
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello" ;
std::string::iterator it = str.begin();
char firstChar = *it;
++it;
++it;
char thirdChar = *it;
std::cout << "First character: " << firstChar
<< std::endl;
std::cout << "Third character: " << thirdChar
<< std::endl;
return 0;
}
|
Output
First character: H
Third character: l
Time complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...