C++ Strings

std::string and its methods.

✍️ 2 exercises in this lesson

std::string manages text and memory for you.

  • Join with + or append().
  • length() / size(), s[i], at(i)
  • substr(pos, len), find(), replace(), insert(), erase()
  • std::to_string(42) and std::stoi("42") convert numbers.

Key Takeaways: C++ Strings

Mastering C++ Strings helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ Strings Code Example

C++
#include <iostream>
#include <string>

int main() {
    std::string s = "Learn C++";
    s += " at CodesInTech";

    std::cout << s << "\n";
    std::cout << "Length: " << s.length() << "\n";
    std::cout << "Found at: " << s.find("C++") << "\n";
    std::cout << s.substr(0, 5) << "\n";

    int lessons = std::stoi("18");
    std::cout << "Lessons: " + std::to_string(lessons + 2) << "\n";
    return 0;
}
Output
Learn C++ at CodesInTech
Length: 24
Found at: 6
Learn
Lessons: 20
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Strings Practice Exercises

Check what you learned in “C++ Strings”.

/ 2 solved
Fill in the blank

Convert a string to an int.

int n = std::("42");
✓ Correct! Not quite. Try again.
Multiple choice

Which method finds the position of a substring?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services