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++ Program to Access Individual Characters in a String #include <iostream> #include <string> // Driver Code int main()
{ std::string str = "Hello" ;
// Accessing individual characters using iterators
std::string::iterator it = str.begin();
char firstChar = *it; // Accessing the first character
// You can also use ++ operator to move the iterator
++it; // Move to the next character
++it; // Move to the third character
char thirdChar = *it;
std::cout << "First character: " << firstChar
<< std::endl;
std::cout << "Third character: " << thirdChar
<< std::endl;
return 0;
} |
First character: H Third character: l
Time complexity: O(1)
Space Complexity: O(1)