Game Development Reference
In-Depth Information
12.9.1 Strings: A Special Kind of Array
The
string
class has a lot of similarities to an array: it consists of a list of characters,
it has a length, and we can access the individual characters using brackets, just like
an array. The
string
class has among others the following methods and properties:
•
int
Length
: determines the length of the string;
•
string
SubString(
int
x,
int
y)
: selects a part of the string indicated by two positions
and returns it as a result;
•
string
Concat(
object
s)
: glues a second string behind it, and returns it as a result.
If the parameter is something other than a string, the method
To S t r i n g
is called on
the object first.
•
bool
Equals(
string
s)
: compares the string character-by-character to another string
and yields
true
if all characters are the same;
•
int
IndexOf(
string
s)
: determines at which spot
s
in
this
appears for the first time;
•
string
Insert(
int
p,
string
s)
: insert
s
into the string at position
p
.
In all cases where a string is returned as a result, it is a new string. The original
string is not changed in any way. This is a conscious choice by the designers of the
class. The
string
type is
immutable
, in other words: once an object of that type is
created it cannot be modified anymore. Of course it is possible to make a modified
copy
, which is exactly what
SubString
,
Concat
and
Insert
do.
Apart from methods, the
string
class also defines operators.
•
The
+
operator with a left
string
argument does exactly the same as the
Concat
method. This allows concatenating strings as
"Hello"+ name
.