π Arrays & Strings in C++
Your Collection of Treasures in Neat Little Boxes
The Big Idea π‘
Imagine you have a toy box with numbered compartments. Each compartment holds exactly one toy, and you can find any toy instantly by knowing its number. Thatβs an array! And when those toys are letters that spell words? Thatβs a string!
π― What Youβll Learn
- Arrays β Your numbered collection boxes
- Multidimensional Arrays β Boxes inside boxes (like a grid)
- std::string Class β C++'s smart word container
- String Operations β Playing with words
π¦ Part 1: Arrays
What is an Array?
Think of a row of mailboxes at an apartment building. Each mailbox:
- Has a number (starting from 0, not 1!)
- Holds one item of the same type
- Is right next to its neighbors
// Creating 5 mailboxes for integers
int scores[5];
// Putting values in each mailbox
scores[0] = 95; // First box
scores[1] = 87; // Second box
scores[2] = 92; // Third box
scores[3] = 78; // Fourth box
scores[4] = 88; // Fifth box
π Creating Arrays
Method 1: Empty boxes, fill later
int ages[4]; // 4 empty boxes
ages[0] = 10; // Now filling them
ages[1] = 12;
ages[2] = 8;
ages[3] = 15;
Method 2: Boxes with gifts already inside
int ages[4] = {10, 12, 8, 15};
Method 3: Let C++ count for you
int ages[] = {10, 12, 8, 15};
// C++ knows there are 4 items!
π’ Array Indexing
SUPER IMPORTANT: Arrays start counting from 0, not 1!
graph TD A["Array: pets"] --> B["Index 0<br>π dog"] A --> C["Index 1<br>π± cat"] A --> D["Index 2<br>π¦ bird"] A --> E["Index 3<br>πΉ hamster"]
string pets[4] = {"dog", "cat", "bird", "hamster"};
cout << pets[0]; // Prints: dog
cout << pets[2]; // Prints: bird
cout << pets[3]; // Prints: hamster
β οΈ Array Danger Zone!
Going outside your array is like opening a mailbox that doesnβt exist!
int nums[3] = {10, 20, 30};
// nums[0] = 10 β
// nums[1] = 20 β
// nums[2] = 30 β
// nums[3] = ??? β DANGER! No box #3!
π Looping Through Arrays
Visit every mailbox automatically!
int scores[5] = {95, 87, 92, 78, 88};
// Visit each box
for(int i = 0; i < 5; i++) {
cout << "Box " << i << ": ";
cout << scores[i] << endl;
}
Output:
Box 0: 95
Box 1: 87
Box 2: 92
Box 3: 78
Box 4: 88
π’ Part 2: Multidimensional Arrays
What Are They?
Remember our mailboxes? Now imagine a whole apartment building with mailboxes on every floor!
- 1D Array = One row of mailboxes
- 2D Array = A grid (rows Γ columns)
- 3D Array = A cube of boxes!
π 2D Arrays: The Grid
Think of a tic-tac-toe board or a spreadsheet!
graph TD A["2D Array: grid[3][3]"] --> B["Row 0"] A --> C["Row 1"] A --> D["Row 2"] B --> B1["[0][0]"] --> B2["[0][1]"] --> B3["[0][2]"] C --> C1["[1][0]"] --> C2["[1][1]"] --> C3["[1][2]"] D --> D1["[2][0]"] --> D2["[2][1]"] --> D3["[2][2]"]
Creating a 2D Array
// A 3x3 grid (like tic-tac-toe)
int grid[3][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6}, // Row 1
{7, 8, 9} // Row 2
};
// Access: grid[row][column]
cout << grid[0][0]; // 1 (top-left)
cout << grid[1][1]; // 5 (center)
cout << grid[2][2]; // 9 (bottom-right)
Real Example: Student Grades
// 3 students, 4 tests each
int grades[3][4] = {
{90, 85, 92, 88}, // Student 0
{78, 82, 79, 85}, // Student 1
{95, 98, 94, 96} // Student 2
};
// Get Student 2's Test 3 score
cout << grades[2][3]; // Output: 96
Looping Through 2D Arrays
// Print entire grid
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 4; col++) {
cout << grades[row][col] << " ";
}
cout << endl; // New line after each row
}
π§ 3D Arrays (Bonus!)
Like a Rubikβs cube β layers of grids!
// 2 floors, each with 3x3 grid
int cube[2][3][3];
// Access: cube[floor][row][column]
cube[0][1][2] = 42; // Floor 0, Row 1, Col 2
π Part 3: The std::string Class
Goodbye Character Arrays, Hello string!
Old way (hard):
char name[20] = "Alice"; // Fixed size, tricky to use
New way (easy!):
#include <string>
string name = "Alice"; // Grows as needed!
π Why string is Amazing
| Old char[] Way | New string Way |
|---|---|
| Fixed size | Grows automatically |
| Manual memory | Handles itself |
| Hard to combine | Easy concatenation |
| Confusing length | Simple .length() |
Creating Strings
#include <string>
using namespace std;
// Different ways to create strings
string empty; // ""
string greeting = "Hello"; // "Hello"
string name("Alice"); // "Alice"
string stars(5, '*'); // "*****"
π String Properties
string word = "Rainbow";
// Length (how many letters)
cout << word.length(); // 7
cout << word.size(); // 7 (same thing!)
// Is it empty?
cout << word.empty(); // false (0)
// Access individual letters
cout << word[0]; // 'R'
cout << word[3]; // 'n'
cout << word.at(6); // 'w' (safer!)
π― at() vs [] - Whatβs the Difference?
string s = "Hi";
// Both work normally:
cout << s[0]; // 'H'
cout << s.at(0); // 'H'
// But with bad index:
cout << s[99]; // β Random garbage!
cout << s.at(99); // β
Throws error (safer!)
π§ Part 4: String Operations
β Combining Strings (Concatenation)
Like snapping LEGO bricks together!
string first = "Hello";
string second = "World";
// Method 1: Plus sign
string result = first + " " + second;
// result = "Hello World"
// Method 2: append()
first.append(" there!");
// first = "Hello there!"
// Method 3: +=
first += "!!!";
// first = "Hello there!!!!"
π Finding Things in Strings
string sentence = "I love pizza and pasta";
// Find position of a word
size_t pos = sentence.find("pizza");
// pos = 7 (pizza starts at index 7)
// Word not found?
pos = sentence.find("burger");
// pos = string::npos (special "not found" value)
// Check if found:
if(sentence.find("love") != string::npos) {
cout << "Found love!";
}
βοΈ Cutting Strings (Substring)
string text = "Hello World";
// substr(start, length)
string piece = text.substr(0, 5);
// piece = "Hello"
string end = text.substr(6, 5);
// end = "World"
// From position to end
string rest = text.substr(6);
// rest = "World"
π Replacing Parts
string msg = "I love cats";
// replace(start, length, new_text)
msg.replace(7, 4, "dogs");
// msg = "I love dogs"
ποΈ Inserting & Erasing
string word = "Hllo";
// Insert at position
word.insert(1, "e");
// word = "Hello"
// Erase from position
word.erase(0, 1);
// word = "ello"
π Comparing Strings
string a = "apple";
string b = "banana";
// Using compare()
if(a.compare(b) < 0) {
cout << "apple comes first";
}
// Simpler way!
if(a < b) {
cout << "apple comes first";
}
if(a == "apple") {
cout << "It's an apple!";
}
π€ Reading Strings from User
string name;
// Single word (stops at space)
cin >> name;
// Full line (includes spaces)
getline(cin, name);
π’ Converting Numbers β Strings
// Number to string
int age = 25;
string ageText = to_string(age);
// ageText = "25"
// String to number
string numStr = "42";
int num = stoi(numStr); // String to int
double d = stod("3.14"); // String to double
π― Quick Reference
graph LR A["C++ Containers"] --> B["Arrays"] A --> C["Strings"] B --> B1["1D: int arr[5]"] B --> B2["2D: int grid[3][3]"] B --> B3["Index starts at 0"] C --> C1["#35;include &lt;string&gt;"] C --> C2["Grows automatically"] C --> C3["Many built-in functions"]
π You Did It!
You now understand:
- β Arrays are numbered boxes holding same-type items
- β Index starts at 0, not 1!
- β 2D arrays are grids (rows Γ columns)
- β
stringis smarter thanchar[] - β Strings can be cut, combined, searched, and compared
Remember: Arrays are like apartment mailboxes. Strings are like magical stretchy word containers. Both help you organize data like a pro! π
