-
Notifications
You must be signed in to change notification settings - Fork 24
/
16.2 AccessingCharElements.cpp
50 lines (41 loc) · 1.26 KB
/
16.2 AccessingCharElements.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <string>
#include <iostream>
int main()
{
using namespace std;
string stlString("Hello String"); // sample
// Access the contents of the string using array syntax
cout << "Display elements in string using array-syntax: " << endl;
for(size_t charCounter = 0;
charCounter < stlString.length();
++ charCounter)
{
cout << "Character[" << charCounter << "] is: ";
cout << stlString[charCounter] << endl;
}
cout << endl;
// Access the contents of a string using iterators
cout << "Display elements in string using iterators: " << endl;
int charOffset = 0;
for(auto charLocator = stlString.cbegin();
charLocator != stlString.cend();
++ charLocator)
{
cout << "Character[" << charOffset ++ << "] is: ";
cout << *charLocator << endl;
}
cout << endl;
// Access contents as a const char*
cout << "The char* representation of the string is: ";
cout << stlString.c_str() << endl;
return 0;
}
/*
// Tip: You may replace the for loop in line 25
// by a range based for loop that's more readable
for(const auto& charLocator : stlString) // range-based for
{
cout << "Character[" << charOffset ++ << "] is: ";
cout << charLocator << endl;
}
*/