📦 Section 2 · Arrays & Pointers 🟢 Beginner MODULE 07

Strings — C-Style & std::string

⏱️ 22 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Section 240%
🎯 What you'll learn: How old-style C strings work as null-terminated char arrays, and — much more importantly — how to use std::string for concatenation, length, indexing, substrings, searching, comparison, and converting between numbers and text.

Two Kinds of Strings in C++

C++ actually has two ways to represent text: the old C-style string inherited from the C language (a plain array of characters), and the modern std::string class from the <string> header. Almost all real C++ code written today uses std::string — but you'll still see C-style strings in older code, so it's worth understanding both.

🧱
C-Style Strings
A char array ending in a special null character '\0'. Manual, error-prone, no built-in safety.
std::string
A full class from <string> that manages its own memory, tracks its own length, and has helpful methods.

C-Style Strings (Historical Context)

A C-style string is just a char array where the last meaningful character is followed by a special null terminator, written '\0'. Functions that print or process C-style strings scan forward until they hit that null character to know where the text ends.

cstyle_strings.cpp — Char Arrays
C++
// cstyle_strings.cpp
#include <iostream>
using namespace std;

int main() {
    char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout << name << endl;

    char greeting[] = "Hi there";  // compiler adds '\0' automatically
    cout << greeting << endl;

    return 0;
}
⚠️
Why C-style strings fell out of favor
Forgetting the null terminator, writing past the array's bounds, or manually managing size are common sources of bugs. Modern C++ solves all of this with std::string, which is what the rest of this lesson focuses on.

std::string Basics

To use std::string, include the <string> header. You can concatenate strings directly with +, and check their length with .length() or the equivalent .size().

string_basics.cpp — Concatenation & Length
C++
// string_basics.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string first = "Ada";
    string last = "Lovelace";
    string full = first + " " + last;

    cout << full << endl;
    cout << "Length: " << full.length() << endl;
    cout << "Size: " << full.size() << endl;

    return 0;
}

.length() and .size() return exactly the same value — they're two names for the same thing. Most C++ programmers use whichever reads more naturally in context.

Indexing & Substrings

You can access individual characters of a std::string with square brackets, exactly like an array. To pull out a piece of a string, use .substr(start, length).

string_slicing.cpp — Indexing & substr()
C++
// string_slicing.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string word = "BitWithBite";

    cout << "First char: " << word[0] << endl;
    cout << "Last char: " << word[word.length() - 1] << endl;
    cout << "Substring(3,4): " << word.substr(3, 4) << endl;

    return 0;
}
Reading substr(3, 4)
The first argument is the starting index, the second is how many characters to take. So word.substr(3, 4) starts at index 3 and grabs 4 characters — on "BitWithBite" that gives you "With".

Searching & Comparing Strings

Use .find() to search for a substring inside a string. It returns the starting index if found, or the special value string::npos if not found. You can compare two strings directly with ==, !=, <, and >.

string_search.cpp — find() & Comparison
C++
// string_search.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string sentence = "C++ is powerful and fast";

    size_t pos = sentence.find("powerful");
    if (pos != string::npos) {
        cout << "Found at index: " << pos << endl;
    } else {
        cout << "Not found" << endl;
    }

    string a = "apple";
    string b = "banana";
    if (a == b) {
        cout << "Equal" << endl;
    } else {
        cout << "Not equal" << endl;
    }

    return 0;
}

size_t is an unsigned integer type used for sizes and indices throughout the C++ standard library — you'll see it a lot alongside strings, arrays, and containers.

Converting Between Numbers and Strings

Use std::to_string() to turn a number into a string, and std::stoi() ("string to int") to turn a numeric string back into an int. There are related functions like stod() for doubles.

string_convert.cpp — to_string() & stoi()
C++
// string_convert.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    int age = 21;
    string ageText = to_string(age);
    cout << "I am " + ageText + " years old" << endl;

    string numStr = "142";
    int num = stoi(numStr);
    cout << "num + 8 = " << (num + 8) << endl;

    return 0;
}
📝
Why not just use cout for everything?
You can print numbers directly with cout without converting them — but to_string() is essential when you need to build a combined string (like a filename, a message, or a formatted label) out of text and numbers together.

Lesson Summary

Let's recap everything you learned in this lesson:

C-style strings are null-terminated char arrays — historical, manual, and error-prone.
std::string from <string> is what modern C++ uses for almost all text.
Concatenate with +, measure with .length() / .size(), index with [].
.substr(start, length) extracts a piece of a string.
.find() searches for a substring and returns string::npos if it isn't found.
to_string() and stoi() convert between numbers and strings.
🧩 Knowledge Check — Lesson 7
Answer all 5 questions to test your understanding. Instant feedback on every answer.
1. Which header must you include to use std::string?
2. What character marks the end of a C-style string?
3. Which function returns a portion of a std::string starting at a given index?
4. What does std::string::find() return if the substring is not found?
5. Which function converts a string like "142" into an int?
💪
Coding Challenge — Lesson 7
Apply what you learned · Beginner Level

Now it's your turn to write real code. Complete the challenge below in your own C++ environment.

Challenge: Palindrome Checker 🔁

Write a C++ program called palindrome.cpp that declares a std::string variable with a word of your choice (for example "level" or "hello"), then checks whether it reads the same forwards and backwards, and prints either "Palindrome!" or "Not a palindrome."

Rules: Compare characters using indexing (word[i]) — do not use a reversing library function. Use .length() to find the string's size. Your loop should stop as soon as it finds a mismatch or safely reach the middle of the string.
💡 Show hints if you're stuck
  • Compare word[i] with word[word.length() - 1 - i]
  • Loop i from 0 up to (but not including) word.length() / 2
  • Use a bool variable, e.g. isPalindrome, starting at true, and set it to false the moment you find a mismatch
  • Print the result with an if/else after the loop finishes
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 7 Complete!

You now know how to manipulate text in C++ with std::string. Next up is the single most important C++ concept — pointers.

Module 07 of 26 Section 2 — Arrays, Strings & Pointers