Lesson 12: Working With Strings

Homework: None



What is a string?
A string is technically an object, but to be more straight-forward it’s a collection of single characters (for example char c = ‘A’; could be in a string) that has different functions available to act upon them. This ‘collection’ of same-type variables is known as an array, and while a string is technically an array of characters, it does have other attributes that distinguish it from a simple character array.


Functions related to string
So strings are different than normal variables, and even their counterpart char arrays (which I will not be teaching since strings are vastly superior in essentially every way). They can be loaded using cin >> stringName, but it’s not advisable. The reason why is because cin “breaks” (stops reading) on white-space. Strings are absolutely allowed to have white space in them (you can put virtually anything into a string). As a result to load a string with multiple words / numbers / symbols, we are going to use:

This code will get an entire “line” (Until enter is hit) and put it into the string (stringName in the example above).

String itself has a number of handy functions in it. It allows for “random access”, which means that we can easily view a single character in a string (similarly to how we would do so with an array in a few more lessons). To view a single letter using this method you could use the following code:

Random access means that we can access any item inside of the array without having to iterate through others first. We will get more into random access when we talk about container types without random access later on.

String.compare()
Using compare in string is one of the first times that I’ve used an object function in this series, so there are subtle syntax points that I want to touch on here. First off, let’s talk about the usage of string.compare() since I did make a small error in the video.

A few subtle things to notice

  • There is a different bit of syntax than we’ve seen in the past. There is a . followed by a function name, then the arguments we’re passing it.
  • The .comes after what is a “normal variable”. This is because strings are actually objects
  • In the future (lesson 21 or 22) when we cover classes, this is a universal topic. Object functions will be called via dot operators.
Lesson 11: Case study – Using loops to make a simple number guessing game
Lesson 13: File Input / Output