String as Character Array

In C++, we can treat text (std::string) as an array of characters. Each character in the text has its own index, which allows us to access individual characters similarly to elements in a vector.

Let's look at an example:

std::string text = "Programming";

In this example, the string text consists of eleven characters. If we want to access the first character of the string, we have two options:

// Using square brackets
char firstChar = text[0];
std::cout << firstChar;  // Output: 'P'

// Or using the at() method
char firstCharAt = text.at(0);
std::cout << firstCharAt;  // Output: 'P'

Similarly, we can access other characters:

char secondChar = text[1];
std::cout << secondChar;  // Output: 'r'

char thirdChar = text.at(2);
std::cout << thirdChar;  // Output: 'o'

The at() method is safer than square brackets because it checks whether the index is not out of range of the string.

Instructions

Store the first character of the variable name in a variable of type char named firstChar. You can use either square brackets or the at() method.

Print the value of the variable firstChar.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/10

String as Character Array | Start Coder