Strings Are Like Arrays, but Different
Some of the things you learned about arrays should remind you of things you learned about strings. Here's some similarities and differences you should keep track of.
Reminders... (array indexes and string indexes are similar)
You should be familiar with the .length()
, .size()
, .find()
, and
.substr()
string functions from an earlier lab. Now that you know more about arrays, you should
recognize that the index numbering for strings and arrays is similar - they both start at 0
and end
at size-1
.
Another Array-like Feature of Strings
Strings can use the same element access notation as arrays. But, unlike arrays, they know their own length. It's
found with .size()
or .length()
remember? So it's even easier to work with them!
Using []
with a string gives you access to the character at that position. Remember to treat the
element like a character!
Here's a few tricks you should take a moment to understand:
The trick used for the "Extra dots:" example is another feature strings have that arrays don't. It's still possible to append one array to another, but it takes extra work, and an array with extra space.
Passing Strings to Functions
Unlike arrays, strings are passed by value. You need to use &
to pass them by reference. Also unlike arrays, you
do not need to pass their size. Strings know their own size.