Introduction to Strings in C++

Welcome back to our C++ course! Today, we'll unravel the data structure known as Strings. Strings are sequences of characters functioning like vectors, thus accommodating elements, enabling access to them at certain positions, removing elements, and much more. Whenever you handle text data in your programs, strings are your go-to tool. Let's dive in!

Suppose you wish to store "Happy Birthday Alice!" on an invitation card in a program. This text can be stored as a string. Like a vector holding characters, a string specializes in holding text, highlighting the significance of textual information in programming.

Declaring a String

To declare a string is analogous to declaring an integer: you use the string keyword, followed by a string variable name. Let's declare a msg string for the invitation message!

#include <iostream>
#include <string>  // Includes the string library to work with strings

int main() {
    std::string msg;  
    std::cout << "The invitation message: " << msg << std::endl;  // Prints "The invitation message:"
    return 0;
}

We declared the string msg, which is currently empty, resulting in the output "The invitation message:".

Strings in C++ must be surrounded by double quotes. Let's also declare and initialize a non-empty string:

#include <iostream>
#include <string>  // Includes the string library to work with strings

int main() {
    std::string greeting = "Hello, World!";  
    std::cout << greeting << std::endl;  // Prints "Hello, World!"
    return 0;
}
Assigning a Value

We'll extend msg, crafting our party invitation using the assignment operator (=).

#include <iostream>
#include <string>

int main() {
    std::string msg;
    msg = "Happy Birthday Alice!";  
    std::cout << "The invitation message: " << msg << std::endl;  // Prints "The invitation message: Happy Birthday Alice!"
    return 0;
}

We've now populated msg to welcome Alice!

Adding and Accessing Elements in a String

Fetching specific string elements is akin to vector elements, facilitated by the index within square brackets [].

#include <iostream>
#include <string>

int main() {
    std::string msg = "Happy Birthday Alice!";
    std::cout << "The first character of the string: " << msg[0] << std::endl;  // Prints "The first character of the string: H"
    return 0;
}

This time, we've retrieved the first character 'H' from the invitation.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal