C++ Online Compiler
Example: Accessing Characters and Length
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Accessing Characters and Length #include
#include
using namespace std; int main() { // Step 1: Declare a sample string string myString = "Example"; // Step 2: Get the length of the string cout << "String: " << myString << endl; cout << "Length: " << myString.length() << endl; // Or myString.size() // Step 3: Access characters using [] operator cout << "First character: " << myString[0] << endl; // 'E' cout << "Last character: " << myString[myString.length() - 1] << endl; // 'e' // Step 4: Access characters using at() method (provides bounds checking) cout << "Character at index 2 (at()): " << myString.at(2) << endl; // 'a' // Step 5: Iterate through the string using a for loop cout << "Characters in string: "; for (int i = 0; i < myString.length(); ++i) { cout << myString[i] << " "; } cout << endl; return 0; }
Output
Clear
ADVERTISEMENTS