Functions and collections · Lesson 8 of 21
Strings and arrays
std::string and its methods, fixed arrays, and std::array.
9 minutes2 games
std::string is text that grows and shrinks by itself, with many ready-made methods. Its characters are indexed from zero, just like arrays.
C++
#include <iostream>
#include <string>
int main() {
std::string course = "SeaCode C++";
std::cout << course.size() << " chars\n";
std::cout << course[0] << " ... " << course.back() << "\n";
std::cout << course.substr(0, 7) << "\n"; // from 0, take 7
std::size_t pos = course.find("C++");
if (pos != std::string::npos) std::cout << "found at " << pos << "\n";
course += " track";
course[0] = 's';
std::cout << course << "\n";
return 0;
}course =
S[0]
e[1]
a[2]
C[3]
o[4]
d[5]
e[6]
[7]
C[8]
+[9]
+[10]
find("C++") found it at index 8.
Arrays
C++
#include <iostream>
#include <array>
int main() {
int raw[4] = {90, 75, 88, 60}; // C-style array: fixed size
std::array<int, 4> scores = {90, 75, 88, 60};
int best = scores[0];
for (std::size_t i = 1; i < scores.size(); i++) {
if (scores[i] > best) best = scores[i];
}
std::cout << "best " << best << " of " << scores.size() << "\n";
std::cout << "raw[2] = " << raw[2] << "\n";
return 0;
}What's the output?
#include <iostream>
#include <string>
int main() {
std::string s = "algorithm";
std::cout << s.substr(2, 4) << s.size() << "\n";
}What will this code print?
Exercise
Count the vowels (a e i o u) in "programming is fun" and print the count.
Expected output: 5
C++
#include <iostream>
#include <string>
int main() {
std::string text = "programming is fun";
int vowels = 0;
std::cout << vowels << "\n";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.