- [Instructor] A primitive string
is a special case of an array.
Not to be confused with the string class
in the standard template library,
the primitive string is often called a C string.
So here we have a working copy of working.cpp
from chapter two of the exercise files.
A primitive string is just a special case
of an array of characters.
So I can create a string like this.
And you'll notice that I've initialized the string
with a literal string in quotes.
And yet, what I'm assigning it to is an array of characters.
So this literal string in quotes is really
an array of characters terminated with a zero,
we'll get to that in a moment.
So I can print this
using the %s substitute in printf.
So I can say s is %s.
And when I build and run,
you'll notice it says s is String.
This %s, it looks for
a null-terminated array of characters,
and it prints it as a string.
So, like I said,
it's just a null-terminated array of characters,
I can initialize it with an initializer list like this.
And you notice that I terminate it with a zero at the end.
But I have those same six characters S-t-r-i-n-g
and when I build and run, it works exactly the same.
So, the literal string in quotes is really just a shorthand
for the separate character elements of the array
terminated with a zero.
So, because it's simply an array of characters
terminated with a zero, a null-terminated string,
I can print each individual element
as the elements of an array.
So I can do this.
And so here, I have a for loop.
We'll talk more about for loops later in this chapter.
But basically, what I'm doing is I have an index,
starts at zero, and it goes until the element is not a zero.
And it increments the index each time,
and I'm using the subscript syntax
to get at each element of the array.
And so when I build and run this,
you notice I'm printing out each element with the array,
and I stop when I get to the zero.
I can do this with pointers if I prefer,
I can say, character pointer.
And then instead of subscripting, the array,
I can de-reference the pointer.
And when I build and run,
you notice this does exactly the same thing.
So we talked about this, when we talked about arrays,
I can use the array to initialize a pointer,
and then I can increment the pointer to look at
each element of the array, as opposed to subscripting it.
So these are two different ways of getting at the same thing
in the array.
And you'll find that both ways are used often in C++.
So this combination of C arrays and pointers
is both common and powerful.
So, a string is simply a C array of characters,
an array is a structure of variables of the same type
stored contiguously,
because the array is guaranteed to be stored contiguously,
it's also easy to iterate with pointers
and C++ syntax lends itself well to this usage.