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.
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!
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:
We'll extend msg
, crafting our party invitation using the assignment operator (=
).
We've now populated msg
to welcome Alice!
Fetching specific string elements is akin to vector elements, facilitated by the index within square brackets []
.
This time, we've retrieved the first character 'H' from the invitation.
Did you accidentally invite "Alics"? Not a problem! Strings can modify characters just like vectors. Remember, the new element must be of type char
so it must be surrounded by single quotes ('
).
Here, we've rectified the typo by changing the 20th character from 's' to 'e'.
Strings in C++ boast handy functions similar to vectors. One of them is size
, which is very helpful to learn the string's length. It returns the number of characters in the string.
Here's how you can utilize it:
Here, we find out the number of letters in the msg
string using the .size()
method. It works pretty much the same as the vector's analogous method.
We can use the +
operator to append one string to another, combining them into a single new string. It is called concatenation. Here's how you can concatenate strings:
In this example, we start with two separate strings part1
and part2
. By using the +
operator, we concatenate them into a single string msg
, resulting in the complete invitation message.
Congratulations on learning about strings in C++! Now, you are equipped with the knowledge to declare strings, add and extract elements, modify characters, and understand string functions. Get ready for practice exercises designed to reinforce your understanding and confidence with strings! Are you ready? Let's go!
