C++ String Class šŸŽÆ

beginner
21 min

C++ String Class šŸŽÆ

Welcome to our deep dive into the C++ String Class! In this lesson, we'll explore the world of strings in C++, a powerful tool for handling text data in your programs. By the end, you'll be able to manipulate, compare, and create strings like a pro! šŸ’”

What is a String in C++? šŸ“

A string in C++ is a sequence of characters, including spaces and special symbols. Unlike C-style strings, C++ strings are objects of the std::string class, which simplifies string handling and offers many useful methods.

Creating a String šŸ’”

To create a string, use the std::string constructor.

cpp
#include <string> int main() { std::string myString = "Hello, World!"; return 0; }

In the above example, we include the <string> header and create a string named myString with the value "Hello, World!".

Working with Strings āœ…

Accessing Characters

To access a character in a string, use square brackets [].

cpp
std::string myString = "Hello, World!"; std::cout << myString[0]; // Output: H

Length of a String

To find the length of a string, use the length() function.

cpp
std::string myString = "Hello, World!"; std::cout << myString.length(); // Output: 13

String Methods šŸ’”

C++ strings offer various methods to manipulate strings easily. Here are a few examples:

Concatenation (+ operator)

cpp
std::string first = "Hello"; std::string second = "World"; std::string result = first + " " + second; std::cout << result; // Output: Hello World

Substring (substr())

cpp
std::string myString = "Hello, World!"; std::string substring = myString.substr(7); std::cout << substring; // Output: World!

Replace (replace())

cpp
std::string myString = "Hello, World!"; myString.replace(0, 5, "Hello Again"); std::cout << myString; // Output: Hello Again, World!

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

How would you access the third character of the string `myString`?

Stay tuned for more lessons on C++ String Class, where we'll explore even more fascinating topics and techniques! šŸš€