A more concise review of the key material from the Strings slides.
Operators
Properties
Methods
Things written with punctuation characters.
For numbers we know the basic math operators
+
, -
, *
, /
, %
, and **
.
+
and []
+
“Concatenation”, a.k.a. “smooshing together”, a.k.a. “adding”.
s1 = 'foo'
s2 = 'bar'
s1 + s2 ⟹ 'foobar'
+
non-strings to strings'My favorite number is ' + 32
⟹ 'My favorite number is 32'
[]
The “index” operator. For accessing individual characters of a string.
s = 'bar'
s[0] ⟹ 'b'
s[1] ⟹ 'a'
s[2] ⟹ 'r'
str[i]
str
has to be a string.
i
has to be a whole number.
Expression as a whole evaluates to a string.
Be very clear about the types of values involved.
The value to the left of the []
is a string.
The value between the [
and ]
is a number.
And the result of evaluating the expression is a string.
Properties are named values attached to other values.
Strings have one property: length
Properties are accessed with a .
and the name of the property.
length
to determine valid indices of an arbitrary string.From 0
to s.length - 1
, inclusive.
s.length
is a number!
In general it’s important to be clear about the types of values.
Bits of functionality attached to a value.
Methods are called on values.
They may also take arguments.
Many methods produce new values when called.
value.method(a, b)
Value can be any expression.
Method is whatever the name of the method is.
a and b, separated by commas, represent two arguments the method expects.
There might be more or less than the two shown here.
substring()
The substring()
method on strings extracts a part of the string.
Takes one or two arguments.
s.substring(i)
Extracts the substring from index i
to the end of the string.
s.substring(i, end)
Extracts the substring from index i
up to, but not including, end
.
s.substring(i)
and
s.substring(i, s.length)
s = 'foobar'
The result is an empty string.
It contains no text and its length is 0.
toUpperCase()
Called on a string, returns a string that is the original string but converted to all upper-case letters.
Note: does not take any arguments.
But you still need ()
after the name when you call it.
toLowerCase()
Called on a string, returns a string that is the original string but converted to all lower-case letters.
Note: also does not take any arguments.
And you still need ()
after the name when you call it.
If s
is a string
s.substring(1)
is also a string
s.substring(1).toUpperCase()
‘foo’ + ‘bar’.toUpperCase()
⟹ 'fooBAR'
(‘foo’ + ‘bar’).toUpperCase()
⟹ 'FOOBAR'